From cd04b4e07a3e912378b84aae299723f4dc036412 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 22:06:19 -0800 Subject: [PATCH 1/8] wip(hashing): sha256 is the only file hash algorithm (ITL-1155) Work in progress: old ITL-1488 tests, xxhash removal, changelog and design issue entry are still to do. Co-Authored-By: Claude Fable 5.2 --- docs/concepts/file-hash-caching.md | 25 +- docs/reference/cli.md | 12 +- docs/reference/hashing.md | 4 +- src/orcapod/cli/warm_cache.py | 9 - src/orcapod/hashing/cache_population.py | 8 +- src/orcapod/hashing/file_hashers.py | 33 +- src/orcapod/hashing/hash_utils.py | 110 ++--- src/orcapod/protocols/hashing_protocols.py | 3 +- .../test_file_hash_sha256_only.py | 430 ++++++++++++++++++ tests/test_hashing/test_file_hashers.py | 23 +- tests/test_hashing/test_hash_label_rule.py | 3 - tests/test_hashing/test_hash_utils.py | 26 +- .../test_hashing/test_postgres_hash_cacher.py | 174 +++---- 13 files changed, 599 insertions(+), 261 deletions(-) create mode 100644 tests/test_hashing/test_file_hash_sha256_only.py diff --git a/docs/concepts/file-hash-caching.md b/docs/concepts/file-hash-caching.md index cb5705e36..3c3fe5ee0 100644 --- a/docs/concepts/file-hash-caching.md +++ b/docs/concepts/file-hash-caching.md @@ -11,9 +11,12 @@ If you have not used `op.File` and `op.Directory` yet, read ## FileHasher, HashCacher, and CachedFileHasher `FileHasher` is the base hasher. When you call `hash_file(path)` on it, it -reads the file's bytes from disk and returns a content hash (SHA-256 by -default, configurable via the `algorithm` argument). It does this every time, -with no memory of previous results. +reads the file's bytes from disk and returns their SHA-256 content hash, with +the label `sha256`. It does this every time, with no memory of previous +results. `sha256` is the only file hash algorithm: `FileHasher(algorithm=...)` +and `hash_file(..., algorithm=...)` refuse any other name with a `ValueError` +that names the algorithm given, and so does a data context file whose file +hasher names another algorithm, when the context is loaded. `HashCacher` is a protocol for any object that maps a `FileHashKey` to a `ContentHash`. The key is a four-field struct: @@ -31,9 +34,10 @@ the write and its conflict check. `FileHashKey.algorithm` is **PROVISIONAL**. Its value is the hash label (`ContentHash.method`) reported by the file hasher's `hash_algorithm` property. -The cache stores each algorithm's hash separately for a given file state. -For example, `orcapod warm-cache --algorithm md5` fills MD5 entries. A later -SHA-256 lookup can fill its own entries alongside them. +Its only accepted value is `sha256`. A cache write under a key with any other +label raises `ValueError`, and a lookup with one is a miss. Entries of another +algorithm that an earlier development version wrote into a cache file are left +in place and never read; the SHA-256 entries are written beside them. A cache write raises `ValueError` if the hash label or digest length is invalid for the key, or if the key already holds a different well-formed hash. Writing @@ -45,8 +49,7 @@ refreshes its timestamp, and logs a warning naming the file and hash algorithm. An incompatible hash returned by a custom cache is also a miss. `orcapod warm-cache --force` skips the cache lookup and recomputes each eligible -file's hash. Content-hashing algorithms read the file's contents. The -`hash_path` algorithm checks that the file exists and hashes its path string. +file's hash from the file's contents. If a new hash differs from a well-formed hash stored for the same key, the cache retains the original entry and the command reports a file error. If a rehash and write conflict occurs while a pipeline hashes a file column, it can @@ -58,10 +61,8 @@ entries. An explicit operation to replace a valid hash is tracked separately (ITL-1547). Let file rewrites advance the modification time to avoid stale hits in the default mode. -The label must name an algorithm whose digest length is fixed: a `hashlib` -algorithm such as `sha256` or `md5`, or `hash_path`, `xxh64` or `crc32`. Every algorithm -`FileHasher` can hash with qualifies. `CachedFileHasher` refuses (`ValueError`) an -inner hasher with any other label when it is built. +`CachedFileHasher` refuses (`ValueError`, naming the label) an inner hasher +whose `hash_algorithm` is not `sha256` when it is built. `CachedFileHasher` wraps a `FileHasher` with any `HashCacher`. When you call `hash_file(path)` on it, it first constructs the key from the file's current diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 8eaef676f..2fe7bb1f4 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -11,18 +11,16 @@ it hashed, found in the cache, skipped by size, or could not process. | --- | --- | | `--min-size MB` | Minimum file size, in units of 1,048,576 bytes. Defaults to `500`. | | `--db-path PATH` | Local SQLite cache path. Defaults to `ORCAPOD_HASH_CACHE_DB` if set, or `~/.orcapod/file_hash_cache.db`. | -| `--algorithm NAME` | Content hash algorithm. Defaults to `sha256`. | | `--buffer-size BYTES` | Read buffer size in bytes. Defaults to `65536`. | | `--workers COUNT` | Number of hashing threads. Defaults to `4`, with a minimum of `1`. | | `--dry-run` | Count files that would be hashed. The scan runs serially and writes no hash entries. Opening the database can initialize a new cache file. | | `--force` | Hash eligible files again, even when they already have a cache entry. With `--dry-run`, include those files in the count. | -!!! warning "Use one hash algorithm per cache" - The cache keys entries by path, modification time, and size. A matching entry - can return a digest from a different algorithm (ITL-1488). Use the same - algorithm in `warm-cache` and in every pipeline that uses that cache. The - default file hasher uses `sha256`. When changing algorithms, clear the - cache before using it again or use a new cache file. +!!! note "One file hash algorithm" + Files are hashed with `sha256`, the only file hash algorithm (ITL-1155), so the + command has no `--algorithm` option. A cache file that an earlier development + version filled with another algorithm can be used as it is: those entries are + left in place and never read, and the files are hashed once more with `sha256`. To preview and then warm the same cache, run: diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index e139f34ce..7765dd0b7 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -93,7 +93,7 @@ The labels of v0.3: | `batch_v1` | the folded source id and record id of `Batch` (site 6b) | `BATCH_FOLD_LABEL`, `core/operators/batch.py` | | `group_v1` | the folded source id and record id of `GroupBy` (site 6b), and the merged source-info token of a data-tag group key | `GROUP_BY_FOLD_LABEL`, `core/operators/group_by.py` | | `join_v1` | the merged source-info token of a key that is a data-tag on several inputs of a `Join` (site 6b) | `JOIN_FOLD_LABEL`, `core/operators/join.py` | -| `sha256` | the file content hash: SHA-256 of the file's bytes | the file hasher's `algorithm` | +| `sha256` | the file content hash: SHA-256 of the file's bytes | `SHA256_ALGORITHM`, `hashing/hash_utils.py` | Where a hash appears, and in which form: @@ -317,7 +317,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. |---|---|---|---|---| | structure hasher | a Python value as a tagged JSON tree | SHA-256 of canonical JSON, `semantic_v1` | every `content_hash()` / `pipeline_hash()`, type and function hash; the names built on schema hashes | `hashing/semantic_hashing/semantic_hasher.py:SemanticAwarePythonHasher._hash_to_content_hash` | | Arrow hasher | a table after the semantic visitor | starfix, `arrow_v1` (a table Orcapod built: float rule on); `hash_table_strict`: `arrow_strict_v1` (a pyarrow table given as a value: every bit counts); `hash_table_ordered`: `arrow_ordered_v1` (a library value's digest: every bit counts); `hash_schema`: `arrow_schema_v1` | row data hashes, entry ids, row keys, default source ids, table values; every schema in an identity | `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_strict`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_ordered`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_schema`, `hashing/arrow_hashers.py:StarfixArrowHasher._digest`, `hashing/starfix_digest.py:_digest_table`, `hashing/starfix_digest.py:digest_schema` | -| file hasher | a file's bytes | the configured digest function, label = its name (`sha256` in the data context; others: ITL-1155) | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put` | +| file hasher | a file's bytes | SHA-256 of the bytes, label `sha256`, the only file hash algorithm: `hash_file`, `FileHasher`, `CachedFileHasher`, the file hash cachers and a data context file refuse any other name (ITL-1155) | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put` | | directory hasher | a directory tree | Merkle tree of SHA-256 entries, `directory_v1`; file leaves taken with their label | `Directory` value hash | `hashing/directory_hashers.py:BasicDirectoryHasher.hash_directory`, `hashing/directory_hashers.py:_hash_dir` | | array value hash | an array: element digest, then order, byte order, struct layout | SHA-256, `ndarray_v1` (the element digest is a step of the same algorithm) | `numpy.ndarray` value hash | `logical_types/numpy_type.py:array_value_digest`, `logical_types/array_format.py:array_digest_v1` | | tensor value hash | element digest, flags, strides, class | SHA-256, `torch_tensor_v1` | `torch.Tensor` value hash | `logical_types/torch_type.py:tensor_digest` | diff --git a/src/orcapod/cli/warm_cache.py b/src/orcapod/cli/warm_cache.py index 31cd5f8ce..186907da0 100644 --- a/src/orcapod/cli/warm_cache.py +++ b/src/orcapod/cli/warm_cache.py @@ -11,8 +11,6 @@ import typer from upath import UPath -from orcapod.hashing.hash_utils import SHA256_ALGORITHM - _DEFAULT_MIN_SIZE_MB: float = 500.0 @@ -32,12 +30,6 @@ def warm_cache( "Defaults to $ORCAPOD_HASH_CACHE_DB or ~/.orcapod/file_hash_cache.db." ), ), - algorithm: str = typer.Option( - SHA256_ALGORITHM, - "--algorithm", - help="Hash algorithm (sha256, xxh64, md5, …). Default: sha256.", - show_default=True, - ), buffer_size: int = typer.Option( 65536, "--buffer-size", @@ -95,7 +87,6 @@ def warm_cache( path, min_size_bytes=min_size_bytes, db_path=_db_path, - algorithm=algorithm, buffer_size=buffer_size, max_workers=max_workers, dry_run=dry_run, diff --git a/src/orcapod/hashing/cache_population.py b/src/orcapod/hashing/cache_population.py index b589fe5f2..8f1f04a25 100644 --- a/src/orcapod/hashing/cache_population.py +++ b/src/orcapod/hashing/cache_population.py @@ -24,7 +24,6 @@ from orcapod.hashing.file_hashers import FileHasher, FileHashKey from orcapod.hashing.hash_cachers import SqliteHashCacher -from orcapod.hashing.hash_utils import SHA256_ALGORITHM from orcapod.types import PathLike logger = logging.getLogger(__name__) @@ -244,7 +243,6 @@ def populate_hash_cache( *, min_size_bytes: int = _DEFAULT_MIN_SIZE_BYTES, db_path: UPath | PathLike | None = None, - algorithm: str = SHA256_ALGORITHM, buffer_size: int = 65536, max_workers: int = _DEFAULT_MAX_WORKERS, dry_run: bool = False, @@ -254,7 +252,8 @@ def populate_hash_cache( """Recursively hash and cache all files >= ``min_size_bytes`` under ``path``. Pre-populates the SQLite file-hash cache so that subsequent pipeline runs - can skip expensive content hashing with a sub-millisecond DB lookup. + can skip expensive content hashing with a sub-millisecond DB lookup. Files + are hashed with ``sha256``, the only file hash algorithm (ITL-1155). All files under ``path`` are visited recursively, including hidden files. Symlinks are skipped. Per-file and per-directory errors are logged as warnings @@ -277,7 +276,6 @@ def populate_hash_cache( supported — SQLite cannot operate on remote filesystems. Defaults to the ``ORCAPOD_HASH_CACHE_DB`` environment variable, or ``~/.orcapod/file_hash_cache.db`` if unset. - algorithm: Hash algorithm passed to ``FileHasher``. Defaults to ``"sha256"``. buffer_size: Read buffer size in bytes passed to ``FileHasher``. Defaults to 65536. max_workers: Number of threads for concurrent per-file hashing. Defaults @@ -335,7 +333,7 @@ def populate_hash_cache( ] ) - hasher = FileHasher(algorithm=algorithm, buffer_size=buffer_size) + hasher = FileHasher(buffer_size=buffer_size) if dry_run: visitor: _HashVisitor | _DryRunVisitor = _DryRunVisitor( cacher, hasher, force=force diff --git a/src/orcapod/hashing/file_hashers.py b/src/orcapod/hashing/file_hashers.py index 1b6439828..b5e571973 100644 --- a/src/orcapod/hashing/file_hashers.py +++ b/src/orcapod/hashing/file_hashers.py @@ -6,6 +6,7 @@ SHA256_ALGORITHM, file_hash_digest_size, hash_file, + require_file_hash_algorithm, ) from orcapod.protocols.hashing_protocols import ( CacherProtocol, @@ -32,7 +33,8 @@ class FileHashKey: mtime_ns: Last-modified time in nanoseconds (``path.stat().st_mtime_ns``). size: File size in bytes (``path.stat().st_size``). algorithm: PROVISIONAL. Hash label of the algorithm (``ContentHash.method`` of the - hash, e.g. ``"sha256"``). + hash): ``"sha256"``, the only file hash algorithm (ITL-1155). A key + with any other label is refused on ``put`` and a miss on ``get``. """ path: UPath @@ -68,8 +70,8 @@ def require_storable(algorithm: str, method: str, digest: bytes) -> int: The validated digest size. Raises: - ValueError: If the labels differ, the label names no algorithm with a fixed - digest length, or the digest has another length. + ValueError: If the labels differ, the label is not ``sha256`` (the only + file hash algorithm), or the digest has another length. """ if str.__eq__(algorithm, method) is not True: raise ValueError( @@ -137,11 +139,19 @@ def parse_stored_file_hash( class FileHasher: - """Hash file content using a configurable algorithm. + """Hash file content with SHA-256. + + ``sha256`` is the only file hash algorithm (ITL-1155): the file content hash + carries the label ``sha256``, and no other algorithm has a defined label. Args: - algorithm: Hashing algorithm to use. Defaults to ``"sha256"``. + algorithm: The hash algorithm. Only ``"sha256"``, the default, is + accepted. buffer_size: Read buffer size in bytes. Defaults to 65536. + + Raises: + ValueError: If ``algorithm`` is not ``"sha256"``; the message names the + algorithm given. """ def __init__( @@ -149,6 +159,7 @@ def __init__( algorithm: str = SHA256_ALGORITHM, buffer_size: int = 65536, ): + require_file_hash_algorithm(algorithm) self.algorithm = algorithm self.buffer_size = buffer_size @@ -189,10 +200,8 @@ class CachedFileHasher: ``FileContentHasherProtocol`` — callers do not need to know which they have. - The inner hasher's label must name an algorithm a cache can store: a - ``hashlib`` algorithm with a fixed digest length, or ``hash_path``, ``xxh64`` - or ``crc32`` (every algorithm ``FileHasher`` can hash with qualifies). Any - other label is refused here, before a file is hashed. + The inner hasher's label must be ``sha256``, the only file hash algorithm + (ITL-1155). Any other label is refused here, before a file is hashed. Args: file_hasher: Inner hasher that performs the actual content hashing. @@ -200,8 +209,8 @@ class CachedFileHasher: ``CacherProtocol[FileHashKey, ContentHash]``. Raises: - ValueError: If ``file_hasher.hash_algorithm`` names no algorithm with a fixed - digest length. + ValueError: If ``file_hasher.hash_algorithm`` is not ``"sha256"``; the + message names the label given. """ def __init__( @@ -209,7 +218,7 @@ def __init__( file_hasher: FileContentHasherProtocol, cacher: "CacherProtocol[FileHashKey, ContentHash]", ) -> None: - _ = file_hash_digest_size(file_hasher.hash_algorithm) + require_file_hash_algorithm(file_hasher.hash_algorithm) self.file_hasher = file_hasher self.cacher = cacher diff --git a/src/orcapod/hashing/hash_utils.py b/src/orcapod/hashing/hash_utils.py index 3e2d7157c..a7c80da97 100644 --- a/src/orcapod/hashing/hash_utils.py +++ b/src/orcapod/hashing/hash_utils.py @@ -3,12 +3,10 @@ import logging import types as _types import typing -import zlib from collections.abc import Callable, Collection from pathlib import Path from typing import TYPE_CHECKING -import xxhash from upath import UPath from orcapod.logical_types.identifier import logical_type_identifier @@ -123,102 +121,76 @@ def _to_path(file_path: PathLike) -> Path | UPath: SHA256_ALGORITHM = "sha256" -_PATH_HASH_ALGORITHM = "hash_path" -_XXH64_ALGORITHM = "xxh64" -_CRC32_ALGORITHM = "crc32" +_SHA256_DIGEST_SIZE = 32 -_FIXED_DIGEST_SIZES = { - _PATH_HASH_ALGORITHM: 32, - _XXH64_ALGORITHM: 8, - _CRC32_ALGORITHM: 4, -} + +def require_file_hash_algorithm(algorithm: object) -> None: + """Require the one file hash algorithm, ``sha256``. + + The file content hash carries the label ``sha256``, the name of the digest + function applied to the file's bytes. No other algorithm has a defined label, + so no other one is accepted (ITL-1155), as the directory hasher accepts none. + + Args: + algorithm: The algorithm name given. + + Raises: + ValueError: If ``algorithm`` is not exactly ``"sha256"``; the message names + the algorithm given. + """ + if not isinstance(algorithm, str) or str.__eq__(algorithm, SHA256_ALGORITHM) is not True: + raise ValueError( + f"Unsupported file hash algorithm {algorithm!r}: " + f"{SHA256_ALGORITHM} is the only file hash algorithm" + ) def file_hash_digest_size(algorithm: str) -> int: """Return the digest length in bytes of a ``hash_file`` hash made with ``algorithm``. Args: - algorithm: An algorithm ``hash_file`` accepts (its hashes' label). + algorithm: The file hash algorithm (its hashes' label): ``"sha256"``. Returns: - The exact length of every digest ``hash_file`` returns for ``algorithm``. + The exact length of every digest ``hash_file`` returns. Raises: - ValueError: If the algorithm name is unsupported or its digest has no - fixed length. + ValueError: If ``algorithm`` is not ``"sha256"``, the only file hash + algorithm. """ - if algorithm in _FIXED_DIGEST_SIZES: - return _FIXED_DIGEST_SIZES[algorithm] - try: - size = hashlib.new(algorithm).digest_size - except (ValueError, TypeError): # hashlib may use TypeError for an embedded NUL - raise ValueError(f"No file hash algorithm named {algorithm!r}") from None - if size == 0: # an extendable-output function (shake_*): no fixed length - raise ValueError( - f"File hash algorithm {algorithm!r} has no fixed digest length" - ) - return size + require_file_hash_algorithm(algorithm) + return _SHA256_DIGEST_SIZE def hash_file( - file_path: PathLike, algorithm=SHA256_ALGORITHM, buffer_size=65536 + file_path: PathLike, algorithm: str = SHA256_ALGORITHM, buffer_size: int = 65536 ) -> ContentHash: - """Calculate the hash of a file using the specified algorithm. + """Calculate the SHA-256 hash of a file's content. Supports both local ``pathlib.Path`` and remote ``UPath`` objects. Args: file_path: Path to the file to hash. - algorithm: Hash algorithm to use — options include: - 'md5', 'sha1', 'sha256', 'sha512', 'xxh64', 'crc32', 'hash_path'. + algorithm: The hash algorithm. ``"sha256"`` is the only file hash + algorithm; anything else is refused. buffer_size: Size of chunks to read from the file at a time. Returns: - A ContentHash with method set to the algorithm name and digest - containing the raw hash bytes. + A ContentHash with method ``"sha256"`` and digest containing the raw + hash bytes. + + Raises: + ValueError: If ``algorithm`` is not ``"sha256"``; the message names the + algorithm given. Raised before the file is looked at. + FileNotFoundError: If ``file_path`` is not a file. """ + require_file_hash_algorithm(algorithm) path = _to_path(file_path) if not path.is_file(): raise FileNotFoundError(f"The file {file_path} does not exist") - # Hash the path string itself rather than file content - if algorithm == _PATH_HASH_ALGORITHM: - hasher = hashlib.sha256() - hasher.update(str(file_path).encode("utf-8")) - return ContentHash(method=algorithm, digest=hasher.digest()) - - if algorithm == _XXH64_ALGORITHM: - hasher = xxhash.xxh64() - with path.open("rb") as file: - while True: - data = file.read(buffer_size) - if not data: - break - hasher.update(data) - return ContentHash(method=algorithm, digest=hasher.digest()) - - if algorithm == _CRC32_ALGORITHM: - crc = 0 - with path.open("rb") as file: - while True: - data = file.read(buffer_size) - if not data: - break - crc = zlib.crc32(data, crc) - return ContentHash( - method=algorithm, - digest=(crc & 0xFFFFFFFF).to_bytes(4, byteorder="big"), - ) - - try: - hasher = hashlib.new(algorithm) - except ValueError: - valid_algorithms = ", ".join(sorted(hashlib.algorithms_available)) - raise ValueError( - f"Invalid algorithm: {algorithm}. Available algorithms: {valid_algorithms}, xxh64, crc32" - ) - + hasher = hashlib.sha256() with path.open("rb") as file: while True: data = file.read(buffer_size) @@ -226,7 +198,7 @@ def hash_file( break hasher.update(data) - return ContentHash(method=algorithm, digest=hasher.digest()) + return ContentHash(method=SHA256_ALGORITHM, digest=hasher.digest()) def _is_in_string(line: str, pos: int) -> bool: diff --git a/src/orcapod/protocols/hashing_protocols.py b/src/orcapod/protocols/hashing_protocols.py index 2467a92c1..02272ae3b 100644 --- a/src/orcapod/protocols/hashing_protocols.py +++ b/src/orcapod/protocols/hashing_protocols.py @@ -146,8 +146,7 @@ def hash_algorithm(self) -> str: A file hash cache uses it to return an entry only to a hasher of the same algorithm (ITL-1488). To be cached (``CachedFileHasher``), the label must - name a ``hashlib`` algorithm with a fixed digest length, or ``hash_path``, - ``xxh64`` or ``crc32``. + be ``sha256``, the only file hash algorithm (ITL-1155). """ ... diff --git a/tests/test_hashing/test_file_hash_sha256_only.py b/tests/test_hashing/test_file_hash_sha256_only.py new file mode 100644 index 000000000..7c6f0e145 --- /dev/null +++ b/tests/test_hashing/test_file_hash_sha256_only.py @@ -0,0 +1,430 @@ +"""``sha256`` is the only file hash algorithm (ITL-1155). + +A hash label names the whole algorithm that produced a digest. The file content +hash keeps the label ``sha256``; no other file hash algorithm has a defined label, +and ``hash_path`` hashed the path text, not the content. So ``hash_file``, the +file hasher classes, the file hash cache and a data context file all refuse every +other algorithm, with an error that names the algorithm given. +""" + +from __future__ import annotations + +import asyncio +import hashlib +import inspect +import json +import shutil +import sqlite3 +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest +from typer.testing import CliRunner +from upath import UPath + +import orcapod as op +from orcapod.cli import app +from orcapod.contexts import get_default_context +from orcapod.contexts.core import ContextResolutionError +from orcapod.contexts.registry import JSONDataContextRegistry +from orcapod.hashing.cache_population import populate_hash_cache +from orcapod.hashing.file_hashers import CachedFileHasher, FileHasher, FileHashKey +from orcapod.hashing.hash_cachers import InMemoryHashCacher, SqliteHashCacher +from orcapod.hashing.hash_utils import hash_file +from orcapod.types import ContentHash, PathLike + +Cacher = InMemoryHashCacher | SqliteHashCacher + +CONTEXTS_DIR = Path(op.__file__).parent / "contexts" + +# Every algorithm the file hasher used to accept besides sha256, a hashlib name it +# never listed, another spelling of sha256, and a name of nothing. +REFUSED_ALGORITHMS = [ + "md5", + "sha1", + "sha512", + "xxh64", + "crc32", + "hash_path", + "sha3_256", + "blake2b", + "SHA256", + "sha-256", + "", + "no_such_algorithm", +] + +# Digest lengths of well-formed hashes of some refused labels. +OTHER_DIGEST_SIZES = {"md5": 16, "sha1": 20, "sha512": 64, "xxh64": 8, "crc32": 4} + + +def _refusal(algorithm: str) -> str: + """The pattern of the error for ``algorithm``: it names it, and sha256.""" + return ( + rf"Unsupported file hash algorithm {algorithm!r}: " + r"sha256 is the only file hash algorithm" + ).replace("\\'", "'") + + +@pytest.fixture +def data_file(tmp_path: Path) -> Path: + path = tmp_path / "data.bin" + path.write_bytes(b"orcapod file hash" * 100) + return path + + +@pytest.fixture(params=["in_memory", "sqlite"]) +def cacher(request: pytest.FixtureRequest, tmp_path: Path) -> Iterator[Cacher]: + if request.param == "in_memory": + yield InMemoryHashCacher() + else: + with SqliteHashCacher(tmp_path / "cache.db") as sqlite_cacher: + yield sqlite_cacher + + +# --------------------------------------------------------------------------- +# hash_file and FileHasher +# --------------------------------------------------------------------------- + + +def test_hash_file_is_the_sha256_of_the_content(data_file: Path) -> None: + expected = ContentHash("sha256", hashlib.sha256(data_file.read_bytes()).digest()) + assert hash_file(data_file) == expected + assert hash_file(data_file, algorithm="sha256") == expected + assert FileHasher().hash_file(data_file) == expected + assert FileHasher(algorithm="sha256").hash_file(data_file) == expected + assert FileHasher().hash_algorithm == "sha256" + + +@pytest.mark.parametrize("algorithm", REFUSED_ALGORITHMS) +def test_hash_file_refuses_every_other_algorithm( + data_file: Path, algorithm: str +) -> None: + with pytest.raises(ValueError) as raised: + hash_file(data_file, algorithm=algorithm) + assert str(raised.value) == ( + f"Unsupported file hash algorithm {algorithm!r}: " + "sha256 is the only file hash algorithm" + ) + + +def test_hash_file_refuses_the_algorithm_before_looking_at_the_file( + tmp_path: Path, +) -> None: + """A refused algorithm is an argument error, whatever the path holds.""" + with pytest.raises(ValueError, match=_refusal("md5")): + hash_file(tmp_path / "missing.bin", algorithm="md5") + + +@pytest.mark.parametrize("algorithm", REFUSED_ALGORITHMS) +def test_file_hasher_refuses_every_other_algorithm_when_built(algorithm: str) -> None: + with pytest.raises(ValueError) as raised: + FileHasher(algorithm=algorithm) + assert repr(algorithm) in str(raised.value) + assert "sha256 is the only file hash algorithm" in str(raised.value) + + +def test_file_hasher_whose_algorithm_was_changed_still_refuses(data_file: Path) -> None: + """Changing the attribute after construction does not get around the rule.""" + hasher = FileHasher() + hasher.algorithm = "md5" + with pytest.raises(ValueError, match=_refusal("md5")): + hasher.hash_file(data_file) + + +def test_path_text_never_enters_a_file_hash(tmp_path: Path) -> None: + """Same content at two paths: one hash. Other content at one path: another.""" + first, second = tmp_path / "a.bin", tmp_path / "b.bin" + first.write_bytes(b"same") + second.write_bytes(b"same") + assert hash_file(first) == hash_file(second) + before = hash_file(first) + first.write_bytes(b"other") + assert hash_file(first) != before + + +# --------------------------------------------------------------------------- +# The file hash cache +# --------------------------------------------------------------------------- + + +class _OtherLabelHasher: + """A custom hasher object that reports another label.""" + + def __init__(self, label: str) -> None: + self.label: str = label + self.calls: int = 0 + + @property + def hash_algorithm(self) -> str: + return self.label + + def hash_file(self, file_path: PathLike) -> ContentHash: + _ = file_path + self.calls += 1 + return ContentHash(self.label, b"\x00" * OTHER_DIGEST_SIZES[self.label]) + + +@pytest.mark.parametrize("label", sorted(OTHER_DIGEST_SIZES)) +def test_cached_file_hasher_refuses_an_inner_hasher_of_another_label( + cacher: Cacher, label: str +) -> None: + inner = _OtherLabelHasher(label) + with pytest.raises(ValueError, match=_refusal(label)): + _ = CachedFileHasher(inner, cacher) + assert inner.calls == 0 + + +def _key(algorithm: str, mtime_ns: int = 1000) -> FileHashKey: + return FileHashKey(UPath("/a/b.txt"), mtime_ns, 100, algorithm) + + +@pytest.mark.parametrize("label", sorted(OTHER_DIGEST_SIZES)) +def test_cacher_refuses_a_put_under_another_label(cacher: Cacher, label: str) -> None: + """A well-formed hash of another algorithm, under its own key: refused.""" + value = ContentHash(label, b"\x01" * OTHER_DIGEST_SIZES[label]) + with pytest.raises(ValueError, match=_refusal(label)): + cacher.put(_key(label), value) + assert cacher.get(_key(label)) is None + assert cacher.get(_key("sha256")) is None + + +def _insert_row(db_path: Path, key: FileHashKey, blob: bytes) -> None: + with sqlite3.connect(db_path) as conn: + conn.execute( + "INSERT INTO file_hash_cache_v2 " + "(path, mtime_ns, size, algorithm, hash, cached_at) " + "VALUES (?, ?, ?, ?, ?, 1)", + (str(key.path), key.mtime_ns, key.size, key.algorithm, blob), + ) + + +def _rows(db_path: Path) -> list[tuple[Any, ...]]: + with sqlite3.connect(db_path) as conn: + return conn.execute( + "SELECT path, mtime_ns, size, algorithm, hash, cached_at " + "FROM file_hash_cache_v2 ORDER BY algorithm" + ).fetchall() + + +@pytest.mark.parametrize("match_mtime", [True, False]) +def test_rows_of_other_algorithms_in_a_cache_file_stay_and_are_never_read( + tmp_path: Path, data_file: Path, match_mtime: bool +) -> None: + """A cache file filled before the restriction: its md5 and xxh64 rows are + untouched, never returned, and the sha256 entry is written beside them.""" + db_path = tmp_path / "cache.db" + path = UPath(data_file).resolve() + stat = path.stat() + old = { + label: FileHashKey(path, stat.st_mtime_ns, stat.st_size, label) + for label in ("md5", "xxh64") + } + with SqliteHashCacher(db_path, match_mtime=match_mtime) as sqlite_cacher: + for label, key in old.items(): + digest = b"\x07" * OTHER_DIGEST_SIZES[label] + _insert_row(db_path, key, label.encode() + b":" + digest) + before = _rows(db_path) + assert len(before) == 2 + + for key in old.values(): + assert sqlite_cacher.get(key) is None + + cached = CachedFileHasher(FileHasher(), sqlite_cacher) + expected = FileHasher().hash_file(data_file) + assert cached.hash_file(data_file) == expected + assert cached.hash_file(data_file) == expected + + after = _rows(db_path) + assert [row for row in after if row[3] != "sha256"] == before + (sha_row,) = [row for row in after if row[3] == "sha256"] + assert sha_row[4] == expected.to_prefixed_digest() + + +def test_warming_a_cache_holding_another_algorithms_rows( + tmp_path: Path, data_file: Path +) -> None: + """An md5 row does not count as cached, and warming leaves it in place.""" + db_path = tmp_path / "cache.db" + path = UPath(data_file).resolve() + stat = path.stat() + with SqliteHashCacher(db_path): + _insert_row( + db_path, + FileHashKey(path, stat.st_mtime_ns, stat.st_size, "md5"), + b"md5:" + b"\x07" * 16, + ) + before = _rows(db_path) + + dry = populate_hash_cache( + data_file.parent, min_size_bytes=0, db_path=db_path, dry_run=True + ) + assert (dry.hashed, dry.already_cached) == (1, 0) + stats = populate_hash_cache(data_file.parent, min_size_bytes=0, db_path=db_path) + assert (stats.hashed, stats.already_cached, stats.errors) == (1, 0, 0) + again = populate_hash_cache(data_file.parent, min_size_bytes=0, db_path=db_path) + assert (again.hashed, again.already_cached) == (0, 1) + + after = _rows(db_path) + assert [row for row in after if row[3] != "sha256"] == before + assert [row[3] for row in after] == ["md5", "sha256"] + + +# --------------------------------------------------------------------------- +# No argument chooses an algorithm any more +# --------------------------------------------------------------------------- + + +def test_populate_hash_cache_takes_no_algorithm() -> None: + assert "algorithm" not in inspect.signature(populate_hash_cache).parameters + + +def test_warm_cache_has_no_algorithm_option(tmp_path: Path, data_file: Path) -> None: + runner = CliRunner() + db_path = tmp_path / "cache.db" + refused = runner.invoke( + app, + ["warm-cache", str(data_file.parent), "--db-path", str(db_path)] + + ["--min-size", "0", "--algorithm", "md5"], + ) + assert refused.exit_code == 2 + assert not db_path.exists() + assert "--algorithm" not in runner.invoke(app, ["warm-cache", "--help"]).output + + done = runner.invoke( + app, + ["warm-cache", str(data_file.parent), "--db-path", str(db_path)] + + ["--min-size", "0"], + ) + assert done.exit_code == 0, done.output + assert [row[3] for row in _rows(db_path)] == ["sha256"] + + +# --------------------------------------------------------------------------- +# A data context file naming another algorithm +# --------------------------------------------------------------------------- + + +def _manifests_naming(tmp_path: Path, config: dict[str, Any]) -> Path: + """Copy the data context files, giving the file hasher ``config``.""" + manifests = tmp_path / "data" + manifests.mkdir() + shutil.copytree(CONTEXTS_DIR / "data" / "schemas", manifests / "schemas") + spec = json.loads((CONTEXTS_DIR / "data" / "v1.json").read_text()) + spec["file_hasher"]["_config"] = config + (manifests / "v1.json").write_text(json.dumps(spec)) + return manifests + + +@pytest.mark.parametrize("algorithm", ["md5", "xxh64", "crc32", "hash_path", "sha512"]) +def test_data_context_file_naming_another_algorithm_is_refused( + tmp_path: Path, algorithm: str +) -> None: + registry = JSONDataContextRegistry( + contexts_dir=_manifests_naming(tmp_path, {"algorithm": algorithm}) + ) + with pytest.raises(ContextResolutionError) as raised: + registry.get_context() + assert ( + f"Unsupported file hash algorithm {algorithm!r}: " + "sha256 is the only file hash algorithm" + ) in str(raised.value) + + +def test_data_context_file_naming_sha256_loads(tmp_path: Path) -> None: + registry = JSONDataContextRegistry( + contexts_dir=_manifests_naming(tmp_path, {"algorithm": "sha256"}) + ) + assert registry.get_context().context_key == "std:v1:default" + + +# --------------------------------------------------------------------------- +# File columns in a pipeline: sha256 on every path, in every arrangement +# --------------------------------------------------------------------------- + +TAG_ORDERS = [("subject", "session"), ("session", "subject")] +LAYOUTS = [ + ("subject", "session", "recording", "notes"), + ("notes", "recording", "session", "subject"), + ("recording", "subject", "notes", "session"), +] + + +def _file_source(folder: Path, tag_order: tuple[str, ...], layout: tuple[str, ...]): + """Two tag columns and two file columns, in the given arrangement.""" + files: dict[str, list[op.File]] = {"recording": [], "notes": []} + for row in range(3): + for column in files: + path = folder / f"{column}_{row}.bin" + path.write_bytes(f"{column} {row}".encode() * 50) + files[column].append(op.File(path)) + columns: dict[str, list[Any]] = { + "subject": ["s1", "s1", "s2"], + "session": [1, 2, 1], + **files, + } + return op.sources.DictSource( + [dict(zip(layout, values)) for values in zip(*(columns[c] for c in layout))], + tag_columns=list(tag_order), + tag_only_columns=True, + source_id="recordings", + ) + + +@op.function_pod(output_keys=("recording_size", "notes_size")) +def file_sizes(recording: op.File, notes: op.File) -> tuple[int, int]: + """The sizes of both files.""" + return recording.stat().st_size, notes.stat().st_size + + +def _file_hashes(folder: Path) -> dict[str, ContentHash]: + return { + path.name: ContentHash("sha256", hashlib.sha256(path.read_bytes()).digest()) + for path in sorted(folder.glob("*.bin")) + } + + +def _rows_of(table: pa.Table) -> list[tuple[Any, ...]]: + names = ("subject", "session", "recording_size", "notes_size") + return sorted(zip(*(table.column(name).to_pylist() for name in names))) + + +@pytest.mark.parametrize("tag_order", TAG_ORDERS) +@pytest.mark.parametrize("layout", LAYOUTS) +def test_file_columns_hash_as_sha256_in_every_arrangement( + tmp_path: Path, tag_order: tuple[str, ...], layout: tuple[str, ...] +) -> None: + """Every file cell's value hash is the sha256 of its content, and the rows a + function pod computes over both file columns are the same, sync and async.""" + source = _file_source(tmp_path, tag_order, layout) + expected = _file_hashes(tmp_path) + hasher = get_default_context().semantic_hasher + seen = 0 + for _, data in source.iter_data(): + for column in ("recording", "notes"): + value = data[column] + assert isinstance(value, op.File) + assert hasher.hash_object(value) == expected[value.name] + seen += 1 + assert seen == 6 + + reference = _file_source(tmp_path, TAG_ORDERS[0], LAYOUTS[0]) + assert source.content_hash() == reference.content_hash() + assert [data.content_hash() for _, data in source.iter_data()] == [ + data.content_hash() for _, data in reference.iter_data() + ] + + want = [("s1", 1, 550, 350), ("s1", 2, 550, 350), ("s2", 1, 550, 350)] + assert _rows_of(file_sizes(source).as_table()) == want + + for run_async in (False, True): + job = op.PipelineJob(name="sizes", database=op.databases.InMemoryArrowDatabase()) + with job: + file_sizes(source, label="sizes") + if run_async: + asyncio.run(job.run_async()) + else: + job.run() + assert _rows_of(job.nodes["sizes"].as_table()) == want diff --git a/tests/test_hashing/test_file_hashers.py b/tests/test_hashing/test_file_hashers.py index d192ac357..3c4f1b9fe 100644 --- a/tests/test_hashing/test_file_hashers.py +++ b/tests/test_hashing/test_file_hashers.py @@ -63,22 +63,6 @@ def test_hash_file_has_digest_bytes(self, sample_file): assert isinstance(result.digest, bytes) assert len(result.digest) == 32 # SHA-256 produces 32 bytes - def test_hash_file_xxh64_returns_content_hash(self, sample_file): - result = hash_file(sample_file, algorithm="xxh64") - assert isinstance(result, ContentHash) - assert result.method == "xxh64" - - def test_hash_file_crc32_returns_content_hash(self, sample_file): - result = hash_file(sample_file, algorithm="crc32") - assert isinstance(result, ContentHash) - assert result.method == "crc32" - assert len(result.digest) == 4 # CRC32 produces 4 bytes - - def test_hash_file_hash_path_returns_content_hash(self, sample_file): - result = hash_file(sample_file, algorithm="hash_path") - assert isinstance(result, ContentHash) - assert result.method == "hash_path" - def test_hash_file_to_string_round_trips(self, sample_file): """ContentHash.to_string() / from_string() preserves method and digest.""" original = hash_file(sample_file) @@ -101,10 +85,9 @@ def test_returns_content_hash(self, file_hasher, sample_file): assert isinstance(result, ContentHash) def test_method_matches_algorithm(self, sample_file): - for algo in ("sha256", "md5"): - hasher = FileHasher(algorithm=algo) - result = hasher.hash_file(sample_file) - assert result.method == algo + hasher = FileHasher(algorithm="sha256") + assert hasher.hash_file(sample_file).method == "sha256" + assert hasher.hash_algorithm == "sha256" def test_digest_is_bytes(self, file_hasher, sample_file): result = file_hasher.hash_file(sample_file) diff --git a/tests/test_hashing/test_hash_label_rule.py b/tests/test_hashing/test_hash_label_rule.py index 22f4c9d4f..fc20d7449 100644 --- a/tests/test_hashing/test_hash_label_rule.py +++ b/tests/test_hashing/test_hash_label_rule.py @@ -804,9 +804,6 @@ def test_identity_does_not_cover_the_derived_content_hash_column(self) -> None: SOURCE_ROOT = Path(orcapod.__file__).parent LABEL_DEFINITIONS = { "sha256": "hashing/hash_utils.py", - "hash_path": "hashing/hash_utils.py", - "xxh64": "hashing/hash_utils.py", - "crc32": "hashing/hash_utils.py", "semantic_v1": "hashing/semantic_hashing/semantic_hasher.py", "arrow_v1": "hashing/arrow_hashers.py", "arrow_ordered_v1": "hashing/arrow_hashers.py", diff --git a/tests/test_hashing/test_hash_utils.py b/tests/test_hashing/test_hash_utils.py index 18203422e..e8329ad60 100644 --- a/tests/test_hashing/test_hash_utils.py +++ b/tests/test_hashing/test_hash_utils.py @@ -183,35 +183,27 @@ def test_nonexistent_file_raises(self, tmp_path): hash_file(tmp_path / "does_not_exist.bin") def test_invalid_algorithm_raises_value_error(self, tmp_path): - """Bogus algorithm name raises ValueError with 'Invalid algorithm' (lines 159-161).""" + """An algorithm other than sha256 raises ValueError naming it (ITL-1155).""" from orcapod.hashing.hash_utils import hash_file import pytest f = tmp_path / "f.bin" f.write_bytes(b"hello") - with pytest.raises(ValueError, match="Invalid algorithm"): + with pytest.raises(ValueError, match="'bogus_algo_xyz'.*sha256 is the only"): hash_file(f, algorithm="bogus_algo_xyz") - def test_hash_path_algorithm(self, tmp_path): - """hash_path hashes the path string, not file content (line 126 area).""" - from orcapod.hashing.hash_utils import hash_file - - f = tmp_path / "f.bin" - f.write_bytes(b"hello") - result = hash_file(f, algorithm="hash_path") - assert result.method == "hash_path" - assert len(result.digest) == 32 - - def test_hash_path_ignores_content(self, tmp_path): - """Two files at the same path but different content hash identically with hash_path.""" + def test_hash_path_algorithm_is_gone(self, tmp_path): + """hash_path hashed the path string, not the content: refused (ITL-1155).""" from orcapod.hashing.hash_utils import hash_file + import pytest f = tmp_path / "f.bin" f.write_bytes(b"content A") - r1 = hash_file(f, algorithm="hash_path") + with pytest.raises(ValueError, match="'hash_path'.*sha256 is the only"): + hash_file(f, algorithm="hash_path") + before = hash_file(f) f.write_bytes(b"content B") - r2 = hash_file(f, algorithm="hash_path") - assert r1.digest == r2.digest + assert hash_file(f) != before class TestIsInString: diff --git a/tests/test_hashing/test_postgres_hash_cacher.py b/tests/test_hashing/test_postgres_hash_cacher.py index 7cccef804..1ace268fb 100644 --- a/tests/test_hashing/test_postgres_hash_cacher.py +++ b/tests/test_hashing/test_postgres_hash_cacher.py @@ -14,7 +14,6 @@ from __future__ import annotations -import hashlib import os import threading from collections.abc import Iterator @@ -370,42 +369,6 @@ def test_zero_threshold_caches_all(self, pg_conninfo): @pytest.mark.postgres class TestPostgresHashCacherConcurrency: - @pytest.mark.parametrize("fail_on_call", [1, 2]) - def test_hash_provider_failure_preserves_valid_row( - self, - pg_conninfo: str, - cacher: PostgresHashCacher, - monkeypatch: pytest.MonkeyPatch, - caplog: pytest.LogCaptureFixture, - fail_on_call: int, - ): - key = make_key() - original = make_hash().to_prefixed_digest() - _insert_raw(pg_conninfo, key, original) - real_new = hashlib.new - calls = 0 - - def transient_new(name: str) -> object: - nonlocal calls - calls += 1 - if calls == fail_on_call: - raise MemoryError("hash constructor allocation failed") - return real_new(name) - - monkeypatch.setattr(hashlib, "new", transient_new) - if fail_on_call == 1: - with pytest.raises(MemoryError, match="allocation failed"): - cacher.put(key, make_hash(bytes(32))) - else: - with pytest.raises(ValueError, match="Different hash"): - cacher.put(key, make_hash(bytes(32))) - assert calls == 1 - with psycopg.connect(pg_conninfo) as conn: - assert conn.execute( - "SELECT hash, cached_at FROM file_hash_cache_v2" - ).fetchone() == (original, 1) - assert not caplog.records - @pytest.mark.parametrize("pg_conninfo", ["UTF8", "SQL_ASCII"], indirect=True) @pytest.mark.parametrize("same_hash", [True, False]) @pytest.mark.parametrize("malformed_existing", [False, True]) @@ -802,71 +765,65 @@ def test_repr_no_password_unchanged(self): # --------------------------------------------------------------------------- -# A hash is returned only for its own algorithm (ITL-1488) +# sha256 is the only file hash algorithm (ITL-1488, ITL-1155) # --------------------------------------------------------------------------- _SIZES = {"sha256": 32, "md5": 16} -def _key_for_algorithm(algorithm: str) -> FileHashKey: +def _key_for_algorithm(algorithm: str, mtime_ns: int = 1000) -> FileHashKey: return FileHashKey( - path=UPath("/a/b.txt"), mtime_ns=1000, size=100, algorithm=algorithm + path=UPath("/a/b.txt"), mtime_ns=mtime_ns, size=100, algorithm=algorithm ) +def _all_rows(pg_conninfo: str) -> list[tuple[object, ...]]: + with connect(pg_conninfo) as conn: + return conn.execute( + "SELECT path, mtime_ns, size, algorithm, hash, cached_at " + "FROM file_hash_cache_v2 ORDER BY algorithm, mtime_ns" + ).fetchall() + + @pytest.mark.postgres class TestPostgresHashCacherAlgorithmLabel: - @pytest.mark.parametrize( - ("first", "second"), [("sha256", "md5"), ("md5", "sha256")] - ) - def test_entry_of_another_label_is_miss( - self, cacher: PostgresHashCacher, first: str, second: str - ): - cacher.put( - _key_for_algorithm(first), ContentHash(first, bytes([1]) * _SIZES[first]) - ) - assert cacher.get(_key_for_algorithm(second)) is None - assert cacher.get(_key_for_algorithm(first)) == ContentHash( - first, bytes([1]) * _SIZES[first] - ) - - @pytest.mark.parametrize( - ("first", "second"), [("sha256", "md5"), ("md5", "sha256")] - ) - def test_put_of_another_algorithm_retains_both_entries( - self, cacher: PostgresHashCacher, first: str, second: str + @pytest.mark.parametrize("match_mtime", [True, False]) + def test_row_of_another_algorithm_stays_and_is_never_read( + self, pg_conninfo: str, match_mtime: bool ): - cacher.put( - _key_for_algorithm(first), ContentHash(first, bytes([1]) * _SIZES[first]) - ) - cacher.put( - _key_for_algorithm(second), ContentHash(second, bytes([2]) * _SIZES[second]) - ) - assert cacher.get(_key_for_algorithm(second)) == ContentHash( - second, bytes([2]) * _SIZES[second] - ) - assert cacher.get(_key_for_algorithm(first)) == ContentHash( - first, bytes([1]) * _SIZES[first] - ) + """A row an earlier version stored under md5: untouched, never returned.""" + old_key = _key_for_algorithm("md5", mtime_ns=2000) + _insert_raw(pg_conninfo, old_key, b"md5:" + b"\x07" * 16) + before = _all_rows(pg_conninfo) + value = ContentHash("sha256", b"\x01" * 32) + with PostgresHashCacher(pg_conninfo, match_mtime=match_mtime) as c: + assert c.get(old_key) is None + assert c.get(_key_for_algorithm("sha256", mtime_ns=2000)) is None + c.put(_key_for_algorithm("sha256"), value) + assert c.get(_key_for_algorithm("sha256")) == value + assert c.get(old_key) is None + # Without the mtime match, the newer md5 row is skipped. + got = c.get(_key_for_algorithm("sha256", mtime_ns=3000)) + assert got == (None if match_mtime else value) + after = _all_rows(pg_conninfo) + assert [row for row in after if row[3] != "sha256"] == before + assert len(after) == 2 - @pytest.mark.parametrize( - ("first", "second"), [("sha256", "md5"), ("md5", "sha256")] - ) - def test_match_mtime_false_skips_newer_entry_of_another_label( - self, pg_conninfo: str, first: str, second: str + @pytest.mark.parametrize("match_mtime", [True, False]) + def test_put_under_another_algorithm_is_refused( + self, pg_conninfo: str, match_mtime: bool ): - c = PostgresHashCacher(pg_conninfo, match_mtime=False) - try: - older = FileHashKey(UPath("/a/b.txt"), 1000, 100, first) - newer = FileHashKey(UPath("/a/b.txt"), 2000, 100, second) - c.put(older, ContentHash(first, bytes([1]) * _SIZES[first])) - c.put(newer, ContentHash(second, bytes([2]) * _SIZES[second])) - assert c.get(FileHashKey(UPath("/a/b.txt"), 3000, 100, first)) == ( - ContentHash(first, bytes([1]) * _SIZES[first]) - ) - finally: - c.close() + """A well-formed md5 hash under an md5 key is refused, naming md5.""" + with PostgresHashCacher(pg_conninfo, match_mtime=match_mtime) as c: + with pytest.raises( + ValueError, + match="Unsupported file hash algorithm 'md5': sha256 is the only", + ): + c.put(_key_for_algorithm("md5"), ContentHash("md5", b"\x01" * 16)) + assert c.get(_key_for_algorithm("md5")) is None + assert c.get(_key_for_algorithm("sha256")) is None + assert _all_rows(pg_conninfo) == [] _CRAFTED_BLOBS = [ @@ -897,19 +854,23 @@ def test_rejects_a_conflict_from_another_label( "ALTER TABLE file_hash_cache_v2 " "ALTER COLUMN algorithm TYPE TEXT COLLATE algorithm_ci" ) + # A stray row whose label the collation equates with the key's label. key = make_key() - original = make_hash() - blob = original.to_prefixed_digest() - _insert_raw(pg_conninfo, key, blob) + stray = FileHashKey(key.path, key.mtime_ns, key.size, "SHA256") + blob = b"SHA256:" + b"\x07" * 32 + _insert_raw(pg_conninfo, stray, blob) with PostgresHashCacher(pg_conninfo, match_mtime=match_mtime) as cache: - other_key = FileHashKey(key.path, key.mtime_ns, key.size, "SHA256") + assert cache.get(key) is None with pytest.raises(ValueError, match="matched a row with algorithm label"): - cache.put(other_key, ContentHash("SHA256", b"\x02" * 32)) - assert cache.get(key) == original + cache.put(key, make_hash()) + # The stray label itself is not a file hash algorithm. + with pytest.raises(ValueError, match="'SHA256'.*sha256 is the only"): + cache.put(stray, ContentHash("SHA256", b"\x02" * 32)) + assert cache.get(stray) is None with connect(pg_conninfo) as conn: assert conn.execute( "SELECT convert_to(algorithm, 'UTF8'), hash, cached_at FROM file_hash_cache_v2" - ).fetchall() == [(b"sha256", blob, 1)] + ).fetchall() == [(b"SHA256", blob, 1)] assert not caplog.records @pytest.mark.parametrize("match_mtime", [True, False]) @@ -1045,17 +1006,17 @@ def test_well_formed_stored_hash_is_read( "sha256", b"\x07" * 32 ) - def test_two_algorithms_written_concurrently_never_cross(self, pg_conninfo: str): - """Concurrent puts of two algorithms on one file: no error, no wrong hit. - - Both hashes remain available throughout the concurrent writes. - """ + def test_concurrent_puts_with_refused_labels_never_reach_the_store( + self, pg_conninfo: str + ): + """Concurrent sha256 puts succeed while md5 puts are refused; no md5 row.""" PostgresHashCacher(pg_conninfo).close() values = { label: ContentHash(label, bytes([n]) * _SIZES[label]) for n, label in ((1, "sha256"), (2, "md5")) } errors: list[Exception] = [] + refused: list[str] = [] barrier = threading.Barrier(8) def write(label: str) -> None: @@ -1066,9 +1027,14 @@ def write(label: str) -> None: c = PostgresHashCacher(pg_conninfo) barrier.wait() for _ in range(20): - c.put(_key_for_algorithm(label), values[label]) - got = c.get(_key_for_algorithm(label)) - assert got == values[label] + if label == "sha256": + c.put(_key_for_algorithm(label), values[label]) + assert c.get(_key_for_algorithm(label)) == values[label] + else: + with pytest.raises(ValueError, match="sha256 is the only"): + c.put(_key_for_algorithm(label), values[label]) + assert c.get(_key_for_algorithm(label)) is None + refused.append(label) except Exception as exc: barrier.abort() errors.append(exc) @@ -1085,13 +1051,15 @@ def write(label: str) -> None: for t in threads: t.join() assert errors == [] + assert len(refused) == 80 reader = PostgresHashCacher(pg_conninfo) try: found = {label: reader.get(_key_for_algorithm(label)) for label in values} finally: reader.close() - assert found == values + assert found == {"sha256": values["sha256"], "md5": None} + assert [row[3] for row in _all_rows(pg_conninfo)] == ["sha256"] _INVALID_LABELS = [ From b55fcb9e0a1a96870469d286f2e3dab6c9b1603a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 23:51:55 -0800 Subject: [PATCH 2/8] fix(hashing)!: finish the SHA-256-only file hasher migration (ITL-1155) --- changelog.d/ITL-1155.md | 12 + docs/concepts/file-hash-caching.md | 4 +- docs/dev/design_issues/ITL-1155-FH1.md | 15 + docs/reference/hashing.md | 2 +- pyproject.toml | 1 - src/orcapod/hashing/hash_utils.py | 5 +- .../test_file_hash_cache_algorithm.py | 295 ++++-------------- .../test_file_hash_sha256_only.py | 12 +- uv.lock | 55 ---- 9 files changed, 108 insertions(+), 293 deletions(-) create mode 100644 changelog.d/ITL-1155.md create mode 100644 docs/dev/design_issues/ITL-1155-FH1.md diff --git a/changelog.d/ITL-1155.md b/changelog.d/ITL-1155.md new file mode 100644 index 000000000..54668da28 --- /dev/null +++ b/changelog.d/ITL-1155.md @@ -0,0 +1,12 @@ +### Breaking changes and migration + +- File hashing now accepts only `sha256`. The `hash_path` mode and all other + algorithms have been removed. Remove other algorithm settings from data context + files or set them to `sha256`. Drop the `--algorithm` option from `warm-cache` + commands and the `algorithm` argument from `populate_hash_cache` calls. + +### Changed + +- Removed the `xxhash` runtime dependency. Existing file hash caches retain their + layout and historical rows. Reads for other algorithms miss and writes raise an + error. SHA-256 digests and their `sha256` label are unchanged. diff --git a/docs/concepts/file-hash-caching.md b/docs/concepts/file-hash-caching.md index 3c3fe5ee0..663498268 100644 --- a/docs/concepts/file-hash-caching.md +++ b/docs/concepts/file-hash-caching.md @@ -15,8 +15,8 @@ reads the file's bytes from disk and returns their SHA-256 content hash, with the label `sha256`. It does this every time, with no memory of previous results. `sha256` is the only file hash algorithm: `FileHasher(algorithm=...)` and `hash_file(..., algorithm=...)` refuse any other name with a `ValueError` -that names the algorithm given, and so does a data context file whose file -hasher names another algorithm, when the context is loaded. +that names the algorithm given. Loading a data context whose file hasher names +another algorithm raises `ContextValidationError` with the same detail. `HashCacher` is a protocol for any object that maps a `FileHashKey` to a `ContentHash`. The key is a four-field struct: diff --git a/docs/dev/design_issues/ITL-1155-FH1.md b/docs/dev/design_issues/ITL-1155-FH1.md new file mode 100644 index 000000000..d1f694fc4 --- /dev/null +++ b/docs/dev/design_issues/ITL-1155-FH1.md @@ -0,0 +1,15 @@ +## Hash labels — file content hashes (ITL-1155) + +### FH1 — File hashing exposed algorithms outside the hash label rule +**Status:** resolved +**Severity:** high +**Issue:** ITL-1155 + +File hashing accepted several digest names as labels, plus `hash_path`, which +hashed the path string. A file content hash label needs to identify the full +procedure that produced it. + +**Fix:** Use SHA-256 over the file bytes and keep the `sha256` label. Reject +other algorithms in file hashers and cache writes. Cache reads for those labels +miss, and the cache schema and historical rows are preserved. Remove the +algorithm selection from cache warming and drop the `xxhash` dependency. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 7765dd0b7..a52cb089b 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -317,7 +317,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. |---|---|---|---|---| | structure hasher | a Python value as a tagged JSON tree | SHA-256 of canonical JSON, `semantic_v1` | every `content_hash()` / `pipeline_hash()`, type and function hash; the names built on schema hashes | `hashing/semantic_hashing/semantic_hasher.py:SemanticAwarePythonHasher._hash_to_content_hash` | | Arrow hasher | a table after the semantic visitor | starfix, `arrow_v1` (a table Orcapod built: float rule on); `hash_table_strict`: `arrow_strict_v1` (a pyarrow table given as a value: every bit counts); `hash_table_ordered`: `arrow_ordered_v1` (a library value's digest: every bit counts); `hash_schema`: `arrow_schema_v1` | row data hashes, entry ids, row keys, default source ids, table values; every schema in an identity | `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_strict`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_ordered`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_schema`, `hashing/arrow_hashers.py:StarfixArrowHasher._digest`, `hashing/starfix_digest.py:_digest_table`, `hashing/starfix_digest.py:digest_schema` | -| file hasher | a file's bytes | SHA-256 of the bytes, label `sha256`, the only file hash algorithm: `hash_file`, `FileHasher`, `CachedFileHasher`, the file hash cachers and a data context file refuse any other name (ITL-1155) | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put` | +| file hasher | a file's bytes | SHA-256 of the bytes, label `sha256`. Hashers, cache writes, and data context loading reject other algorithms. Cache lookups for other labels miss (ITL-1155). | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put` | | directory hasher | a directory tree | Merkle tree of SHA-256 entries, `directory_v1`; file leaves taken with their label | `Directory` value hash | `hashing/directory_hashers.py:BasicDirectoryHasher.hash_directory`, `hashing/directory_hashers.py:_hash_dir` | | array value hash | an array: element digest, then order, byte order, struct layout | SHA-256, `ndarray_v1` (the element digest is a step of the same algorithm) | `numpy.ndarray` value hash | `logical_types/numpy_type.py:array_value_digest`, `logical_types/array_format.py:array_digest_v1` | | tensor value hash | element digest, flags, strides, class | SHA-256, `torch_tensor_v1` | `torch.Tensor` value hash | `logical_types/torch_type.py:tensor_digest` | diff --git a/pyproject.toml b/pyproject.toml index ff983e388..73b662747 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,6 @@ name = "orcapod" description = "Intuitive and powerful library for highly reproducible scientific data pipeline" dynamic = ["version"] dependencies = [ - "xxhash", "networkx", "pandas>=2.2.3,<3", "pyarrow>=22.0.0", diff --git a/src/orcapod/hashing/hash_utils.py b/src/orcapod/hashing/hash_utils.py index a7c80da97..e26eadbbd 100644 --- a/src/orcapod/hashing/hash_utils.py +++ b/src/orcapod/hashing/hash_utils.py @@ -138,7 +138,10 @@ def require_file_hash_algorithm(algorithm: object) -> None: ValueError: If ``algorithm`` is not exactly ``"sha256"``; the message names the algorithm given. """ - if not isinstance(algorithm, str) or str.__eq__(algorithm, SHA256_ALGORITHM) is not True: + if ( + not isinstance(algorithm, str) + or str.__eq__(algorithm, SHA256_ALGORITHM) is not True + ): raise ValueError( f"Unsupported file hash algorithm {algorithm!r}: " f"{SHA256_ALGORITHM} is the only file hash algorithm" diff --git a/tests/test_hashing/test_file_hash_cache_algorithm.py b/tests/test_hashing/test_file_hash_cache_algorithm.py index 6277d06df..45228dc88 100644 --- a/tests/test_hashing/test_file_hash_cache_algorithm.py +++ b/tests/test_hashing/test_file_hash_cache_algorithm.py @@ -1,14 +1,11 @@ """A cached file hash is used only for the algorithm that made it (ITL-1488). -The file hash cache keys an entry by path, modified time, size and algorithm. A -hash made with one algorithm must never be returned for another: the file's hash -enters identities and stored values, so a cache filled with ``md5`` must not -change what the default ``sha256`` hasher returns. +The cache accepts only SHA-256. Historical rows from other algorithms must +stay untouched and must never be returned by the SHA-256 lookup. """ from __future__ import annotations -import hashlib import sqlite3 import time from collections.abc import Iterator @@ -22,15 +19,12 @@ from typing_extensions import override from upath import UPath -from orcapod.hashing.cache_population import populate_hash_cache from orcapod.hashing.file_hashers import CachedFileHasher, FileHasher, FileHashKey from orcapod.hashing.hash_cachers import InMemoryHashCacher, SqliteHashCacher from orcapod.types import ContentHash, PathLike Cacher = InMemoryHashCacher | SqliteHashCacher -ALGORITHM_ORDERS = [("sha256", "md5"), ("md5", "sha256"), ("sha256", "xxh64")] - @pytest.fixture def data_file(tmp_path: Path) -> Path: @@ -48,104 +42,42 @@ def cacher(request: pytest.FixtureRequest, tmp_path: Path) -> Iterator[Cacher]: yield sqlite_cacher -@pytest.mark.parametrize(("first", "second"), ALGORITHM_ORDERS) -def test_shared_cache_returns_each_algorithms_own_hash( - cacher: Cacher, data_file: Path, first: str, second: str -): - """Two algorithms over one cache, one file: each gets its own hash, in any order.""" - expected = { - algorithm: FileHasher(algorithm=algorithm).hash_file(data_file) - for algorithm in (first, second) - } - hashers = { - algorithm: CachedFileHasher(FileHasher(algorithm=algorithm), cacher) - for algorithm in (first, second) - } - - # Fill with the first, then ask for the second, then both again (a hit each). - for algorithm in (first, second, first, second): - result = hashers[algorithm].hash_file(data_file) - assert result == expected[algorithm] - assert result.method == algorithm - - -@pytest.mark.parametrize(("first", "second"), ALGORITHM_ORDERS) -def test_warm_cache_with_another_algorithm_does_not_change_the_hash( - tmp_path: Path, data_file: Path, first: str, second: str -): - """The issue's case: warm-cache with one algorithm, then hash with another.""" - db_path = tmp_path / "cache.db" - populate_hash_cache( - data_file.parent, min_size_bytes=0, db_path=db_path, algorithm=first - ) - - with SqliteHashCacher(db_path) as sqlite_cacher: - result = CachedFileHasher( - FileHasher(algorithm=second), sqlite_cacher - ).hash_file(data_file) - assert result == FileHasher(algorithm=second).hash_file(data_file) - - -@pytest.mark.parametrize(("first", "second"), ALGORITHM_ORDERS) -def test_warm_cache_counts_another_algorithms_entry_as_not_cached( - tmp_path: Path, data_file: Path, first: str, second: str -): - """An entry of another algorithm is not 'already cached' for warm-cache.""" - db_path = tmp_path / "cache.db" - populate_hash_cache( - data_file.parent, min_size_bytes=0, db_path=db_path, algorithm=first - ) - - dry = populate_hash_cache( - data_file.parent, - min_size_bytes=0, - db_path=db_path, - algorithm=second, - dry_run=True, - ) - assert (dry.hashed, dry.already_cached) == (1, 0) - - stats = populate_hash_cache( - data_file.parent, min_size_bytes=0, db_path=db_path, algorithm=second - ) - assert (stats.hashed, stats.already_cached) == (1, 0) - - again = populate_hash_cache( - data_file.parent, min_size_bytes=0, db_path=db_path, algorithm=second - ) - assert (again.hashed, again.already_cached) == (0, 1) - - -# --------------------------------------------------------------------------- -# The cachers: a key's label selects its own algorithm's entry -# --------------------------------------------------------------------------- - - def _key(algorithm: str, mtime_ns: int = 1000) -> FileHashKey: return FileHashKey(UPath("/a/b.txt"), mtime_ns, 100, algorithm) -@pytest.mark.parametrize(("first", "second"), [("sha256", "md5"), ("md5", "sha256")]) -def test_cacher_entry_of_another_label_is_miss(cacher: Cacher, first: str, second: str): - cacher.put(_key(first), _hash_of(first, 1)) - assert cacher.get(_key(second)) is None - assert cacher.get(_key(first)) == _hash_of(first, 1) +@pytest.mark.parametrize("label", ["md5", "xxh64"]) +def test_cacher_refuses_another_label_beside_a_sha256_entry(cacher: Cacher, label: str): + value = _hash_of("sha256") + cacher.put(_key("sha256"), value) + + assert cacher.get(_key(label)) is None + with pytest.raises(ValueError, match=f"Unsupported file hash algorithm {label!r}"): + cacher.put(_key(label), _hash_of(label)) + + assert cacher.get(_key(label)) is None + assert cacher.get(_key("sha256")) == value -@pytest.mark.parametrize("kind", ["in_memory", "sqlite"]) -@pytest.mark.parametrize(("first", "second"), [("sha256", "md5"), ("md5", "sha256")]) -def test_match_mtime_false_skips_a_newer_entry_of_another_label( - tmp_path: Path, kind: str, first: str, second: str +@pytest.mark.parametrize("label", ["md5", "xxh64"]) +def test_sqlite_without_mtime_skips_a_newer_row_of_another_label( + tmp_path: Path, label: str ): - """Without the mtime match, the newest entry OF THE KEY'S LABEL is returned.""" - if kind == "in_memory": - c = InMemoryHashCacher(match_mtime=False) - else: - c = SqliteHashCacher(tmp_path / "cache.db", match_mtime=False) - c.put(_key(first, 1000), _hash_of(first, 1)) - c.put(_key(second, 2000), _hash_of(second, 2)) - assert c.get(_key(first, 3000)) == _hash_of(first, 1) - assert c.get(_key(second, 3000)) == _hash_of(second, 2) + db_path = tmp_path / "cache.db" + old_key = _key(label, mtime_ns=2000) + old_blob = _hash_of(label).to_prefixed_digest() + with SqliteHashCacher(db_path, match_mtime=False) as cache: + _insert_raw(db_path, old_blob, key=old_key) + assert cache.get(_key("sha256", mtime_ns=3000)) is None + value = _hash_of("sha256") + cache.put(_key("sha256"), value) + assert cache.get(_key("sha256", mtime_ns=3000)) == value + assert cache.get(old_key) is None + with sqlite3.connect(db_path) as conn: + assert conn.execute( + "SELECT mtime_ns, hash, cached_at FROM file_hash_cache_v2 WHERE algorithm=?", + (label,), + ).fetchall() == [(old_key.mtime_ns, old_blob, 1)] @pytest.fixture @@ -164,11 +96,11 @@ def restore_file_handlers() -> Iterator[None]: registry.register(Directory, directory_handler) -@pytest.mark.parametrize("warmed_with", ["md5", "xxh64"]) -def test_default_file_hash_ignores_a_cache_warmed_with_another_algorithm( - restore_file_handlers, tmp_path: Path, data_file: Path, warmed_with: str +@pytest.mark.parametrize("label", ["md5", "xxh64"]) +def test_default_file_hash_ignores_a_legacy_row_of_another_algorithm( + restore_file_handlers, tmp_path: Path, data_file: Path, label: str ): - """The issue's report: 'warm-cache --force --algorithm md5', then caching on.""" + """Enabling caching over a historical cache preserves the file value hash.""" from orcapod.contexts import enable_file_hash_caching, get_default_context from orcapod.logical_types.file_type import File @@ -176,13 +108,11 @@ def test_default_file_hash_ignores_a_cache_warmed_with_another_algorithm( uncached = hasher.hash_object(File(data_file)) db_path = tmp_path / "cache.db" - populate_hash_cache( - data_file.parent, - min_size_bytes=0, - db_path=db_path, - algorithm=warmed_with, - force=True, - ) + path = UPath(data_file).resolve() + stat = path.stat() + key = FileHashKey(path, stat.st_mtime_ns, stat.st_size, label) + with SqliteHashCacher(db_path): + _insert_raw(db_path, _hash_of(label).to_prefixed_digest(), key=key) enable_file_hash_caching(db_path=db_path) assert hasher.hash_object(File(data_file)) == uncached # filled by this call @@ -192,8 +122,8 @@ def test_default_file_hash_ignores_a_cache_warmed_with_another_algorithm( class _CountingHasher: """A ``FileHasher`` that counts the files it actually reads.""" - def __init__(self, algorithm: str) -> None: - self.inner: FileHasher = FileHasher(algorithm=algorithm) + def __init__(self) -> None: + self.inner: FileHasher = FileHasher() self.reads: int = 0 @property @@ -238,7 +168,7 @@ def test_cached_file_hasher_treats_invalid_custom_hits_as_misses( data_file: Path, cached_value: object ): legacy_cache = _LegacyCacher() - file_hasher = _CountingHasher(FileHasher().hash_algorithm) + file_hasher = _CountingHasher() cached_hasher = CachedFileHasher(file_hasher, legacy_cache) path = UPath(data_file.resolve()) stat = path.stat() @@ -253,7 +183,7 @@ def test_cached_file_hasher_treats_invalid_custom_hits_as_misses( def test_cached_file_hasher_uses_a_valid_custom_hit_without_reading(data_file: Path): legacy_cache = _LegacyCacher() - file_hasher = _CountingHasher(FileHasher().hash_algorithm) + file_hasher = _CountingHasher() cached_hasher = CachedFileHasher(file_hasher, legacy_cache) path = UPath(data_file.resolve()) stat = path.stat() @@ -266,23 +196,6 @@ def test_cached_file_hasher_uses_a_valid_custom_hit_without_reading(data_file: P assert file_hasher.reads == 0 -@pytest.mark.parametrize(("first", "second"), ALGORITHM_ORDERS) -def test_alternating_algorithms_keep_both_cached( - cacher: Cacher, data_file: Path, first: str, second: str -): - """Read the file once per algorithm, including when the cache is shared.""" - inner = {algorithm: _CountingHasher(algorithm) for algorithm in (first, second)} - cached = { - algorithm: CachedFileHasher(inner[algorithm], cacher) - for algorithm in (first, second) - } - for algorithm in (first, second, first, second): - assert cached[algorithm].hash_file(data_file) == FileHasher( - algorithm=algorithm - ).hash_file(data_file) - assert (inner[first].reads, inner[second].reads) == (1, 1) - - def test_conflicting_hash_is_refused_and_identical_hash_is_a_noop(cacher: Cacher): key = _key("sha256") original = _hash_of("sha256", 1) @@ -340,10 +253,7 @@ def put(value: ContentHash) -> bool: DIGEST_SIZES = { "sha256": 32, "md5": 16, - "sha1": 20, - "sha512": 64, "xxh64": 8, - "crc32": 4, } @@ -388,43 +298,28 @@ def test_mislabelled_put_cannot_poison_a_cached_file_hasher( UPath(data_file).resolve(), stat.st_mtime_ns, stat.st_size, "sha256" ) with pytest.raises(ValueError): - cacher.put(key, FileHasher(algorithm="md5").hash_file(data_file)) + cacher.put(key, _hash_of("md5")) hashed = CachedFileHasher(FileHasher(), cacher).hash_file(data_file) assert hashed == FileHasher().hash_file(data_file) -@pytest.mark.parametrize( - ("label", "length"), [("sha256", 31), ("sha256", 33), ("md5", 32)] -) -def test_put_of_a_digest_of_the_wrong_length_is_refused( - cacher: Cacher, label: str, length: int -): +@pytest.mark.parametrize("length", [31, 33]) +def test_put_of_a_digest_of_the_wrong_length_is_refused(cacher: Cacher, length: int): + key = _key("sha256") with pytest.raises(ValueError, match="digest"): - cacher.put(_key(label), ContentHash(label, b"\x01" * length)) - assert cacher.get(_key(label)) is None + cacher.put(key, ContentHash(key.algorithm, b"\x01" * length)) + assert cacher.get(key) is None -def test_put_of_an_unknown_algorithm_is_refused(cacher: Cacher): - with pytest.raises(ValueError): - cacher.put(_key("no_such_algo"), ContentHash("no_such_algo", b"\x01" * 32)) - - -@pytest.mark.parametrize("label", sorted(DIGEST_SIZES)) -def test_every_supported_algorithm_round_trips( - cacher: Cacher, data_file: Path, label: str -): - value = FileHasher(algorithm=label).hash_file(data_file) - assert len(value.digest) == DIGEST_SIZES[label] - cacher.put(_key(label), value) - assert cacher.get(_key(label)) == value - - -def _insert_raw(db_path: Path, blob: bytes | str, algorithm: str = "sha256") -> None: +def _insert_raw( + db_path: Path, blob: bytes | str, *, key: FileHashKey | None = None +) -> None: + key = key if key is not None else _key("sha256") with sqlite3.connect(db_path) as conn: conn.execute( "INSERT INTO file_hash_cache_v2 (path, mtime_ns, size, algorithm, hash, cached_at) " "VALUES (?, ?, ?, ?, ?, 1)", - ("/a/b.txt", 1000, 100, algorithm, blob), + (str(key.path), key.mtime_ns, key.size, key.algorithm, blob), ) @@ -459,26 +354,30 @@ def test_sqlite_rejects_a_conflict_from_another_label( caplog: pytest.LogCaptureFixture, ): db_path = tmp_path / "cache.db" - original = _hash_of("sha256") - blob = original.to_prefixed_digest() + stray = _key("SHA256") + blob = ContentHash(stray.algorithm, b"\x07" * 32).to_prefixed_digest() with SqliteHashCacher(db_path, match_mtime=match_mtime) as cache: - _insert_raw(db_path, blob) + _insert_raw(db_path, blob, key=stray) adapter_key = (str, sqlite3.PrepareProtocol) previous_adapter = sqlite3.adapters.get(adapter_key) - sqlite3.register_adapter(str, str.lower) + # Make SQLite bind the SHA-256 key to the stray label for this transaction. + sqlite3.register_adapter( + str, lambda value: "SHA256" if value == "sha256" else value + ) try: with pytest.raises(ValueError, match="matched a row with algorithm label"): - cache.put(_key("SHA256"), ContentHash("SHA256", b"\x02" * 32)) + cache.put(_key("sha256"), _hash_of("sha256")) finally: if previous_adapter is None: del sqlite3.adapters[adapter_key] else: sqlite3.register_adapter(str, previous_adapter) - assert cache.get(_key("sha256")) == original + assert cache.get(_key("sha256")) is None + assert cache.get(stray) is None with sqlite3.connect(db_path) as conn: assert conn.execute( "SELECT algorithm, hash, cached_at FROM file_hash_cache_v2" - ).fetchall() == [("sha256", blob, 1)] + ).fetchall() == [("SHA256", blob, 1)] assert not caplog.records @@ -576,46 +475,6 @@ def test_sqlite_reads_a_well_formed_stored_hash(tmp_path: Path): assert c.get(_key("sha256")) == ContentHash("sha256", b"\x07" * 32) -@pytest.mark.parametrize("fail_on_call", [1, 2]) -def test_sqlite_hash_provider_failure_preserves_valid_row( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - caplog: pytest.LogCaptureFixture, - fail_on_call: int, -): - db_path = tmp_path / "cache.db" - key = _key("sha256") - original = _hash_of("sha256").to_prefixed_digest() - real_new = hashlib.new - calls = 0 - - def transient_new(name: str) -> object: - nonlocal calls - calls += 1 - if calls == fail_on_call: - raise MemoryError("hash constructor allocation failed") - return real_new(name) - - with SqliteHashCacher(db_path) as cache: - _insert_raw(db_path, original) - monkeypatch.setattr(hashlib, "new", transient_new) - if fail_on_call == 1: - with pytest.raises(MemoryError, match="allocation failed"): - cache.put(key, _hash_of("sha256", 2)) - else: - with pytest.raises(ValueError, match="Different hash"): - cache.put(key, _hash_of("sha256", 2)) - assert calls == 1 - with sqlite3.connect(db_path) as conn: - assert conn.execute( - "SELECT hash, cached_at FROM file_hash_cache_v2" - ).fetchone() == ( - original, - 1, - ) - assert not caplog.records - - @pytest.mark.parametrize("operation", ["get", "put"]) @pytest.mark.parametrize("match_mtime", [True, False]) def test_sqlite_invalid_utf8_text_is_a_miss_or_repaired( @@ -677,31 +536,11 @@ def test_sqlite_read_with_an_invalid_label_is_a_miss( db_path = tmp_path / "c.db" with SqliteHashCacher(db_path, match_mtime=match_mtime) as c: _insert_raw( - db_path, label.encode("utf-8") + b":" + b"\x07" * 32, algorithm=label + db_path, label.encode("utf-8") + b":" + b"\x07" * 32, key=_key(label) ) assert c.get(_key(label)) is None -@pytest.mark.parametrize("kind", ["in_memory", "sqlite"]) -def test_unknown_hashlib_algorithm_is_value_error_on_put_and_a_miss_on_read( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, kind: str -): - def refusing_new(name: str) -> object: - raise ValueError(f"Unsupported hash type {name}") - - db_path = tmp_path / "c.db" - c: Cacher = ( - InMemoryHashCacher() if kind == "in_memory" else SqliteHashCacher(db_path) - ) - if isinstance(c, SqliteHashCacher): - _insert_raw(db_path, b"refused_algo:" + b"\x07" * 32, algorithm="refused_algo") - monkeypatch.setattr(hashlib, "new", refusing_new) - - with pytest.raises(ValueError): - c.put(_key("refused_algo"), ContentHash("refused_algo", b"\x01" * 32)) - assert c.get(_key("refused_algo")) is None - - class _CustomLabelHasher: """A hasher whose label names no ``hashlib`` algorithm.""" diff --git a/tests/test_hashing/test_file_hash_sha256_only.py b/tests/test_hashing/test_file_hash_sha256_only.py index 7c6f0e145..37f1d8b19 100644 --- a/tests/test_hashing/test_file_hash_sha256_only.py +++ b/tests/test_hashing/test_file_hash_sha256_only.py @@ -27,7 +27,7 @@ import orcapod as op from orcapod.cli import app from orcapod.contexts import get_default_context -from orcapod.contexts.core import ContextResolutionError +from orcapod.contexts.core import ContextValidationError from orcapod.contexts.registry import JSONDataContextRegistry from orcapod.hashing.cache_population import populate_hash_cache from orcapod.hashing.file_hashers import CachedFileHasher, FileHasher, FileHashKey @@ -325,7 +325,7 @@ def test_data_context_file_naming_another_algorithm_is_refused( registry = JSONDataContextRegistry( contexts_dir=_manifests_naming(tmp_path, {"algorithm": algorithm}) ) - with pytest.raises(ContextResolutionError) as raised: + with pytest.raises(ContextValidationError) as raised: registry.get_context() assert ( f"Unsupported file hash algorithm {algorithm!r}: " @@ -417,12 +417,14 @@ def test_file_columns_hash_as_sha256_in_every_arrangement( ] want = [("s1", 1, 550, 350), ("s1", 2, 550, 350), ("s2", 1, 550, 350)] - assert _rows_of(file_sizes(source).as_table()) == want + assert _rows_of(file_sizes.pod(source).as_table()) == want for run_async in (False, True): - job = op.PipelineJob(name="sizes", database=op.databases.InMemoryArrowDatabase()) + job = op.PipelineJob( + name="sizes", database=op.databases.InMemoryArrowDatabase() + ) with job: - file_sizes(source, label="sizes") + file_sizes.pod(source, label="sizes") if run_async: asyncio.run(job.run_async()) else: diff --git a/uv.lock b/uv.lock index 1eac880a4..8411335e7 100644 --- a/uv.lock +++ b/uv.lock @@ -1877,7 +1877,6 @@ dependencies = [ { name = "tzdata" }, { name = "universal-pathlib" }, { name = "uuid-utils" }, - { name = "xxhash" }, ] [package.optional-dependencies] @@ -1972,7 +1971,6 @@ requires-dist = [ { name = "tzdata", specifier = ">=2024.1" }, { name = "universal-pathlib", specifier = ">=0.3.8" }, { name = "uuid-utils", specifier = ">=0.11.1" }, - { name = "xxhash" }, ] provides-extras = ["all", "postgresql", "ray", "redis", "spiraldb", "torch"] @@ -3785,59 +3783,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/38/34/98a2f52245f4d47be93b580dae5f9861ef58977d73a79eb47c58f1ad1f3a/xmltodict-1.0.4-py3-none-any.whl", hash = "sha256:a4a00d300b0e1c59fc2bfccb53d7b2e88c32f200df138a0dd2229f842497026a", size = 13580, upload-time = "2026-02-22T02:21:21.039Z" }, ] -[[package]] -name = "xxhash" -version = "3.5.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/00/5e/d6e5258d69df8b4ed8c83b6664f2b47d30d2dec551a29ad72a6c69eafd31/xxhash-3.5.0.tar.gz", hash = "sha256:84f2caddf951c9cbf8dc2e22a89d4ccf5d86391ac6418fe81e3c67d0cf60b45f", size = 84241, upload-time = "2024-08-17T09:20:38.972Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b8/c7/afed0f131fbda960ff15eee7f304fa0eeb2d58770fade99897984852ef23/xxhash-3.5.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:02c2e816896dc6f85922ced60097bcf6f008dedfc5073dcba32f9c8dd786f3c1", size = 31969, upload-time = "2024-08-17T09:18:00.852Z" }, - { url = "https://files.pythonhosted.org/packages/8c/0c/7c3bc6d87e5235672fcc2fb42fd5ad79fe1033925f71bf549ee068c7d1ca/xxhash-3.5.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:6027dcd885e21581e46d3c7f682cfb2b870942feeed58a21c29583512c3f09f8", size = 30800, upload-time = "2024-08-17T09:18:01.863Z" }, - { url = "https://files.pythonhosted.org/packages/04/9e/01067981d98069eec1c20201f8c145367698e9056f8bc295346e4ea32dd1/xxhash-3.5.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1308fa542bbdbf2fa85e9e66b1077eea3a88bef38ee8a06270b4298a7a62a166", size = 221566, upload-time = "2024-08-17T09:18:03.461Z" }, - { url = "https://files.pythonhosted.org/packages/d4/09/d4996de4059c3ce5342b6e1e6a77c9d6c91acce31f6ed979891872dd162b/xxhash-3.5.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c28b2fdcee797e1c1961cd3bcd3d545cab22ad202c846235197935e1df2f8ef7", size = 201214, upload-time = "2024-08-17T09:18:05.616Z" }, - { url = "https://files.pythonhosted.org/packages/62/f5/6d2dc9f8d55a7ce0f5e7bfef916e67536f01b85d32a9fbf137d4cadbee38/xxhash-3.5.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:924361811732ddad75ff23e90efd9ccfda4f664132feecb90895bade6a1b4623", size = 429433, upload-time = "2024-08-17T09:18:06.957Z" }, - { url = "https://files.pythonhosted.org/packages/d9/72/9256303f10e41ab004799a4aa74b80b3c5977d6383ae4550548b24bd1971/xxhash-3.5.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:89997aa1c4b6a5b1e5b588979d1da048a3c6f15e55c11d117a56b75c84531f5a", size = 194822, upload-time = "2024-08-17T09:18:08.331Z" }, - { url = "https://files.pythonhosted.org/packages/34/92/1a3a29acd08248a34b0e6a94f4e0ed9b8379a4ff471f1668e4dce7bdbaa8/xxhash-3.5.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:685c4f4e8c59837de103344eb1c8a3851f670309eb5c361f746805c5471b8c88", size = 208538, upload-time = "2024-08-17T09:18:10.332Z" }, - { url = "https://files.pythonhosted.org/packages/53/ad/7fa1a109663366de42f724a1cdb8e796a260dbac45047bce153bc1e18abf/xxhash-3.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:dbd2ecfbfee70bc1a4acb7461fa6af7748ec2ab08ac0fa298f281c51518f982c", size = 216953, upload-time = "2024-08-17T09:18:11.707Z" }, - { url = "https://files.pythonhosted.org/packages/35/02/137300e24203bf2b2a49b48ce898ecce6fd01789c0fcd9c686c0a002d129/xxhash-3.5.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:25b5a51dc3dfb20a10833c8eee25903fd2e14059e9afcd329c9da20609a307b2", size = 203594, upload-time = "2024-08-17T09:18:13.799Z" }, - { url = "https://files.pythonhosted.org/packages/23/03/aeceb273933d7eee248c4322b98b8e971f06cc3880e5f7602c94e5578af5/xxhash-3.5.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:a8fb786fb754ef6ff8c120cb96629fb518f8eb5a61a16aac3a979a9dbd40a084", size = 210971, upload-time = "2024-08-17T09:18:15.824Z" }, - { url = "https://files.pythonhosted.org/packages/e3/64/ed82ec09489474cbb35c716b189ddc1521d8b3de12b1b5ab41ce7f70253c/xxhash-3.5.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:a905ad00ad1e1c34fe4e9d7c1d949ab09c6fa90c919860c1534ff479f40fd12d", size = 415050, upload-time = "2024-08-17T09:18:17.142Z" }, - { url = "https://files.pythonhosted.org/packages/71/43/6db4c02dcb488ad4e03bc86d70506c3d40a384ee73c9b5c93338eb1f3c23/xxhash-3.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:963be41bcd49f53af6d795f65c0da9b4cc518c0dd9c47145c98f61cb464f4839", size = 192216, upload-time = "2024-08-17T09:18:18.779Z" }, - { url = "https://files.pythonhosted.org/packages/22/6d/db4abec29e7a567455344433d095fdb39c97db6955bb4a2c432e486b4d28/xxhash-3.5.0-cp311-cp311-win32.whl", hash = "sha256:109b436096d0a2dd039c355fa3414160ec4d843dfecc64a14077332a00aeb7da", size = 30120, upload-time = "2024-08-17T09:18:20.009Z" }, - { url = "https://files.pythonhosted.org/packages/52/1c/fa3b61c0cf03e1da4767213672efe186b1dfa4fc901a4a694fb184a513d1/xxhash-3.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:b702f806693201ad6c0a05ddbbe4c8f359626d0b3305f766077d51388a6bac58", size = 30003, upload-time = "2024-08-17T09:18:21.052Z" }, - { url = "https://files.pythonhosted.org/packages/6b/8e/9e6fc572acf6e1cc7ccb01973c213f895cb8668a9d4c2b58a99350da14b7/xxhash-3.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:c4dcb4120d0cc3cc448624147dba64e9021b278c63e34a38789b688fd0da9bf3", size = 26777, upload-time = "2024-08-17T09:18:22.809Z" }, - { url = "https://files.pythonhosted.org/packages/07/0e/1bfce2502c57d7e2e787600b31c83535af83746885aa1a5f153d8c8059d6/xxhash-3.5.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:14470ace8bd3b5d51318782cd94e6f94431974f16cb3b8dc15d52f3b69df8e00", size = 31969, upload-time = "2024-08-17T09:18:24.025Z" }, - { url = "https://files.pythonhosted.org/packages/3f/d6/8ca450d6fe5b71ce521b4e5db69622383d039e2b253e9b2f24f93265b52c/xxhash-3.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:59aa1203de1cb96dbeab595ded0ad0c0056bb2245ae11fac11c0ceea861382b9", size = 30787, upload-time = "2024-08-17T09:18:25.318Z" }, - { url = "https://files.pythonhosted.org/packages/5b/84/de7c89bc6ef63d750159086a6ada6416cc4349eab23f76ab870407178b93/xxhash-3.5.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:08424f6648526076e28fae6ea2806c0a7d504b9ef05ae61d196d571e5c879c84", size = 220959, upload-time = "2024-08-17T09:18:26.518Z" }, - { url = "https://files.pythonhosted.org/packages/fe/86/51258d3e8a8545ff26468c977101964c14d56a8a37f5835bc0082426c672/xxhash-3.5.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:61a1ff00674879725b194695e17f23d3248998b843eb5e933007ca743310f793", size = 200006, upload-time = "2024-08-17T09:18:27.905Z" }, - { url = "https://files.pythonhosted.org/packages/02/0a/96973bd325412feccf23cf3680fd2246aebf4b789122f938d5557c54a6b2/xxhash-3.5.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f2f2c61bee5844d41c3eb015ac652a0229e901074951ae48581d58bfb2ba01be", size = 428326, upload-time = "2024-08-17T09:18:29.335Z" }, - { url = "https://files.pythonhosted.org/packages/11/a7/81dba5010f7e733de88af9555725146fc133be97ce36533867f4c7e75066/xxhash-3.5.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9d32a592cac88d18cc09a89172e1c32d7f2a6e516c3dfde1b9adb90ab5df54a6", size = 194380, upload-time = "2024-08-17T09:18:30.706Z" }, - { url = "https://files.pythonhosted.org/packages/fb/7d/f29006ab398a173f4501c0e4977ba288f1c621d878ec217b4ff516810c04/xxhash-3.5.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:70dabf941dede727cca579e8c205e61121afc9b28516752fd65724be1355cc90", size = 207934, upload-time = "2024-08-17T09:18:32.133Z" }, - { url = "https://files.pythonhosted.org/packages/8a/6e/6e88b8f24612510e73d4d70d9b0c7dff62a2e78451b9f0d042a5462c8d03/xxhash-3.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e5d0ddaca65ecca9c10dcf01730165fd858533d0be84c75c327487c37a906a27", size = 216301, upload-time = "2024-08-17T09:18:33.474Z" }, - { url = "https://files.pythonhosted.org/packages/af/51/7862f4fa4b75a25c3b4163c8a873f070532fe5f2d3f9b3fc869c8337a398/xxhash-3.5.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:3e5b5e16c5a480fe5f59f56c30abdeba09ffd75da8d13f6b9b6fd224d0b4d0a2", size = 203351, upload-time = "2024-08-17T09:18:34.889Z" }, - { url = "https://files.pythonhosted.org/packages/22/61/8d6a40f288f791cf79ed5bb113159abf0c81d6efb86e734334f698eb4c59/xxhash-3.5.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:149b7914451eb154b3dfaa721315117ea1dac2cc55a01bfbd4df7c68c5dd683d", size = 210294, upload-time = "2024-08-17T09:18:36.355Z" }, - { url = "https://files.pythonhosted.org/packages/17/02/215c4698955762d45a8158117190261b2dbefe9ae7e5b906768c09d8bc74/xxhash-3.5.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:eade977f5c96c677035ff39c56ac74d851b1cca7d607ab3d8f23c6b859379cab", size = 414674, upload-time = "2024-08-17T09:18:38.536Z" }, - { url = "https://files.pythonhosted.org/packages/31/5c/b7a8db8a3237cff3d535261325d95de509f6a8ae439a5a7a4ffcff478189/xxhash-3.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fa9f547bd98f5553d03160967866a71056a60960be00356a15ecc44efb40ba8e", size = 192022, upload-time = "2024-08-17T09:18:40.138Z" }, - { url = "https://files.pythonhosted.org/packages/78/e3/dd76659b2811b3fd06892a8beb850e1996b63e9235af5a86ea348f053e9e/xxhash-3.5.0-cp312-cp312-win32.whl", hash = "sha256:f7b58d1fd3551b8c80a971199543379be1cee3d0d409e1f6d8b01c1a2eebf1f8", size = 30170, upload-time = "2024-08-17T09:18:42.163Z" }, - { url = "https://files.pythonhosted.org/packages/d9/6b/1c443fe6cfeb4ad1dcf231cdec96eb94fb43d6498b4469ed8b51f8b59a37/xxhash-3.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:fa0cafd3a2af231b4e113fba24a65d7922af91aeb23774a8b78228e6cd785e3e", size = 30040, upload-time = "2024-08-17T09:18:43.699Z" }, - { url = "https://files.pythonhosted.org/packages/0f/eb/04405305f290173acc0350eba6d2f1a794b57925df0398861a20fbafa415/xxhash-3.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:586886c7e89cb9828bcd8a5686b12e161368e0064d040e225e72607b43858ba2", size = 26796, upload-time = "2024-08-17T09:18:45.29Z" }, - { url = "https://files.pythonhosted.org/packages/c9/b8/e4b3ad92d249be5c83fa72916c9091b0965cb0faeff05d9a0a3870ae6bff/xxhash-3.5.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:37889a0d13b0b7d739cfc128b1c902f04e32de17b33d74b637ad42f1c55101f6", size = 31795, upload-time = "2024-08-17T09:18:46.813Z" }, - { url = "https://files.pythonhosted.org/packages/fc/d8/b3627a0aebfbfa4c12a41e22af3742cf08c8ea84f5cc3367b5de2d039cce/xxhash-3.5.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:97a662338797c660178e682f3bc180277b9569a59abfb5925e8620fba00b9fc5", size = 30792, upload-time = "2024-08-17T09:18:47.862Z" }, - { url = "https://files.pythonhosted.org/packages/c3/cc/762312960691da989c7cd0545cb120ba2a4148741c6ba458aa723c00a3f8/xxhash-3.5.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f85e0108d51092bdda90672476c7d909c04ada6923c14ff9d913c4f7dc8a3bc", size = 220950, upload-time = "2024-08-17T09:18:49.06Z" }, - { url = "https://files.pythonhosted.org/packages/fe/e9/cc266f1042c3c13750e86a535496b58beb12bf8c50a915c336136f6168dc/xxhash-3.5.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:cd2fd827b0ba763ac919440042302315c564fdb797294d86e8cdd4578e3bc7f3", size = 199980, upload-time = "2024-08-17T09:18:50.445Z" }, - { url = "https://files.pythonhosted.org/packages/bf/85/a836cd0dc5cc20376de26b346858d0ac9656f8f730998ca4324921a010b9/xxhash-3.5.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:82085c2abec437abebf457c1d12fccb30cc8b3774a0814872511f0f0562c768c", size = 428324, upload-time = "2024-08-17T09:18:51.988Z" }, - { url = "https://files.pythonhosted.org/packages/b4/0e/15c243775342ce840b9ba34aceace06a1148fa1630cd8ca269e3223987f5/xxhash-3.5.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:07fda5de378626e502b42b311b049848c2ef38784d0d67b6f30bb5008642f8eb", size = 194370, upload-time = "2024-08-17T09:18:54.164Z" }, - { url = "https://files.pythonhosted.org/packages/87/a1/b028bb02636dfdc190da01951d0703b3d904301ed0ef6094d948983bef0e/xxhash-3.5.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c279f0d2b34ef15f922b77966640ade58b4ccdfef1c4d94b20f2a364617a493f", size = 207911, upload-time = "2024-08-17T09:18:55.509Z" }, - { url = "https://files.pythonhosted.org/packages/80/d5/73c73b03fc0ac73dacf069fdf6036c9abad82de0a47549e9912c955ab449/xxhash-3.5.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:89e66ceed67b213dec5a773e2f7a9e8c58f64daeb38c7859d8815d2c89f39ad7", size = 216352, upload-time = "2024-08-17T09:18:57.073Z" }, - { url = "https://files.pythonhosted.org/packages/b6/2a/5043dba5ddbe35b4fe6ea0a111280ad9c3d4ba477dd0f2d1fe1129bda9d0/xxhash-3.5.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:bcd51708a633410737111e998ceb3b45d3dbc98c0931f743d9bb0a209033a326", size = 203410, upload-time = "2024-08-17T09:18:58.54Z" }, - { url = "https://files.pythonhosted.org/packages/a2/b2/9a8ded888b7b190aed75b484eb5c853ddd48aa2896e7b59bbfbce442f0a1/xxhash-3.5.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:3ff2c0a34eae7df88c868be53a8dd56fbdf592109e21d4bfa092a27b0bf4a7bf", size = 210322, upload-time = "2024-08-17T09:18:59.943Z" }, - { url = "https://files.pythonhosted.org/packages/98/62/440083fafbc917bf3e4b67c2ade621920dd905517e85631c10aac955c1d2/xxhash-3.5.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:4e28503dccc7d32e0b9817aa0cbfc1f45f563b2c995b7a66c4c8a0d232e840c7", size = 414725, upload-time = "2024-08-17T09:19:01.332Z" }, - { url = "https://files.pythonhosted.org/packages/75/db/009206f7076ad60a517e016bb0058381d96a007ce3f79fa91d3010f49cc2/xxhash-3.5.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a6c50017518329ed65a9e4829154626f008916d36295b6a3ba336e2458824c8c", size = 192070, upload-time = "2024-08-17T09:19:03.007Z" }, - { url = "https://files.pythonhosted.org/packages/1f/6d/c61e0668943a034abc3a569cdc5aeae37d686d9da7e39cf2ed621d533e36/xxhash-3.5.0-cp313-cp313-win32.whl", hash = "sha256:53a068fe70301ec30d868ece566ac90d873e3bb059cf83c32e76012c889b8637", size = 30172, upload-time = "2024-08-17T09:19:04.355Z" }, - { url = "https://files.pythonhosted.org/packages/96/14/8416dce965f35e3d24722cdf79361ae154fa23e2ab730e5323aa98d7919e/xxhash-3.5.0-cp313-cp313-win_amd64.whl", hash = "sha256:80babcc30e7a1a484eab952d76a4f4673ff601f54d5142c26826502740e70b43", size = 30041, upload-time = "2024-08-17T09:19:05.435Z" }, - { url = "https://files.pythonhosted.org/packages/27/ee/518b72faa2073f5aa8e3262408d284892cb79cf2754ba0c3a5870645ef73/xxhash-3.5.0-cp313-cp313-win_arm64.whl", hash = "sha256:4811336f1ce11cac89dcbd18f3a25c527c16311709a89313c3acaf771def2d4b", size = 26801, upload-time = "2024-08-17T09:19:06.547Z" }, -] - [[package]] name = "yarl" version = "1.25.1" From c25ff7d2b1d2a1b45ce97c2c29fd47c345e3fca3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 00:43:05 -0800 Subject: [PATCH 3/8] fix(hashing): enforce SHA-256 across custom file hash routes --- changelog.d/ITL-1155.md | 3 +- docs/dev/design_issues/ITL-1155-FH1.md | 8 +- src/orcapod/contexts/registry.py | 9 +- src/orcapod/hashing/directory_hashers.py | 13 +- src/orcapod/hashing/file_hashers.py | 33 ++--- src/orcapod/hashing/hash_cachers.py | 25 ++-- src/orcapod/hashing/postgres_hash_cacher.py | 18 ++- .../semantic_hashing/builtin_handlers.py | 9 +- src/orcapod/protocols/hashing_protocols.py | 4 +- tests/test_contexts/test_data_context_v1.py | 35 +++++ .../test_file_hash_cache_algorithm.py | 128 ++++++++++++++++++ .../test_hashing/test_postgres_hash_cacher.py | 14 +- 12 files changed, 254 insertions(+), 45 deletions(-) diff --git a/changelog.d/ITL-1155.md b/changelog.d/ITL-1155.md index 54668da28..a3a3de9bb 100644 --- a/changelog.d/ITL-1155.md +++ b/changelog.d/ITL-1155.md @@ -9,4 +9,5 @@ - Removed the `xxhash` runtime dependency. Existing file hash caches retain their layout and historical rows. Reads for other algorithms miss and writes raise an - error. SHA-256 digests and their `sha256` label are unchanged. + error. Clearing a persistent cache deletes only its `sha256` rows. SHA-256 + digests and their `sha256` label are unchanged. diff --git a/docs/dev/design_issues/ITL-1155-FH1.md b/docs/dev/design_issues/ITL-1155-FH1.md index d1f694fc4..066449d9b 100644 --- a/docs/dev/design_issues/ITL-1155-FH1.md +++ b/docs/dev/design_issues/ITL-1155-FH1.md @@ -10,6 +10,8 @@ hashed the path string. A file content hash label needs to identify the full procedure that produced it. **Fix:** Use SHA-256 over the file bytes and keep the `sha256` label. Reject -other algorithms in file hashers and cache writes. Cache reads for those labels -miss, and the cache schema and historical rows are preserved. Remove the -algorithm selection from cache warming and drop the `xxhash` dependency. +other algorithms in built-in and custom file hashers and cache writes. Verify +computed file hashes before returning, caching, or folding them into a directory +hash. Cache reads for other labels miss, and clearing a persistent cache +preserves historical rows. Remove the algorithm selection from cache warming and +drop the `xxhash` dependency. diff --git a/src/orcapod/contexts/registry.py b/src/orcapod/contexts/registry.py index 020cafee1..8466d54f8 100644 --- a/src/orcapod/contexts/registry.py +++ b/src/orcapod/contexts/registry.py @@ -414,6 +414,8 @@ def _create_context_from_spec(self, spec: dict[str, Any]) -> DataContext: instantiated automatically and become available as ``_ref`` targets for later components in the same file. """ + from orcapod.hashing.hash_utils import require_file_hash_algorithm + try: context_key = spec["context_key"] version = spec["version"] @@ -460,7 +462,12 @@ def _create_context_from_spec(self, spec: dict[str, Any]) -> DataContext: continue if isinstance(value, dict) and "_class" in value: logger.debug(f"Creating {key} for context {version}") - ref_lut[key] = parse_objectspec(value, ref_lut=ref_lut) + component = parse_objectspec(value, ref_lut=ref_lut) + if key == "file_hasher": + require_file_hash_algorithm( + getattr(component, "hash_algorithm", None) + ) + ref_lut[key] = component # The value handlers of the logical types join the core handlers of the # context file; they may refer to its components (``file_hasher`` ...). diff --git a/src/orcapod/hashing/directory_hashers.py b/src/orcapod/hashing/directory_hashers.py index c0175e783..985c1e4c4 100644 --- a/src/orcapod/hashing/directory_hashers.py +++ b/src/orcapod/hashing/directory_hashers.py @@ -10,7 +10,8 @@ from upath import UPath -from orcapod.hashing.hash_utils import SHA256_ALGORITHM +from orcapod.hashing.file_hashers import require_file_hash +from orcapod.hashing.hash_utils import SHA256_ALGORITHM, require_file_hash_algorithm from orcapod.protocols.hashing_protocols import FileContentHasherProtocol from orcapod.types import ContentHash, PathLike @@ -104,6 +105,7 @@ def _hash_dir( entry_bytes = b"symlink\x00" + name_bytes + b"\x00" + target.encode("utf-8") elif child.is_file(): file_hash = file_hasher.hash_file(child) + _ = require_file_hash(SHA256_ALGORITHM, file_hash.method, file_hash.digest) # The file hash comes from another hasher: it enters with its label. entry_bytes = ( b"file\x00" + name_bytes + b"\x00" + file_hash.to_prefixed_digest() @@ -142,8 +144,8 @@ class BasicDirectoryHasher: on repeated calls (e.g. across pipeline runs). Args: - file_hasher: Hasher used to compute the ``ContentHash`` for each file leaf in - the tree. Any object with a ``hash_file(path) -> ContentHash`` method. + file_hasher: File content hasher reporting the ``sha256`` algorithm, + used to compute the ``ContentHash`` for each file leaf. algorithm: Hash algorithm for structural (Merkle entry and node) hashing. Only ``"sha256"`` (the default) is accepted: the label ``directory_v1`` names the SHA-256 procedure and nothing else. @@ -167,13 +169,14 @@ def __init__( algorithm: str = SHA256_ALGORITHM, buffer_size: int = 65536, ) -> None: - if algorithm != SHA256_ALGORITHM: + if str.__eq__(SHA256_ALGORITHM, algorithm) is not True: raise ValueError( f"{DIRECTORY_HASH_LABEL} is defined over {SHA256_ALGORITHM} " f"entry and node digests; got algorithm {algorithm!r}" ) + require_file_hash_algorithm(file_hasher.hash_algorithm) self.file_hasher = file_hasher - self.algorithm = algorithm + self.algorithm = SHA256_ALGORITHM self.buffer_size = buffer_size def hash_directory( diff --git a/src/orcapod/hashing/file_hashers.py b/src/orcapod/hashing/file_hashers.py index b5e571973..2dbe5bcdd 100644 --- a/src/orcapod/hashing/file_hashers.py +++ b/src/orcapod/hashing/file_hashers.py @@ -54,15 +54,14 @@ def stored_hash_format(label: str) -> tuple[bytes, int] | None: return label.encode("ascii") + b":", digest_size -def require_storable(algorithm: str, method: str, digest: bytes) -> int: - """Require a hash of the key's algorithm and return the validated digest size. +def require_file_hash(algorithm: str, method: str, digest: bytes) -> int: + """Require a file hash of the expected algorithm and return its digest size. - Every file hash cacher calls this first in ``put``, so a store never holds a - value under another algorithm's key (ITL-1488): the value's label must be the - key's, and its digest exactly that algorithm's length. + The value's label must match the expected algorithm, and its digest must be + exactly that algorithm's length. Args: - algorithm: The key's algorithm label. + algorithm: The expected algorithm label. method: The incoming hash's algorithm label. digest: The incoming hash's raw digest. @@ -74,10 +73,7 @@ def require_storable(algorithm: str, method: str, digest: bytes) -> int: file hash algorithm), or the digest has another length. """ if str.__eq__(algorithm, method) is not True: - raise ValueError( - f"A {method!r} hash cannot be stored under a key whose label is " - f"{algorithm!r}" - ) + raise ValueError(f"File hash has label {method!r}, expected {algorithm!r}") size = file_hash_digest_size(algorithm) if len(digest) != size: raise ValueError(f"A {algorithm!r} digest is {size} bytes, not {len(digest)}") @@ -91,7 +87,7 @@ def serialize_storable_file_hash( # Snapshot the raw buffer so validation and serialization use the same bytes, # even if a subclass overrides digest access or bytes operations. digest = memoryview(value.digest).tobytes() - digest_size = require_storable(algorithm, value.method, digest) + digest_size = require_file_hash(algorithm, value.method, digest) prefix = algorithm.encode("ascii") + b":" return prefix, digest_size, prefix + digest @@ -194,7 +190,8 @@ class CachedFileHasher: the inner hasher's ``hash_algorithm``. Each algorithm has its own entry. 3. Accept a hit only if it is a ``ContentHash`` with the expected label and digest length. - 4. On miss: delegate to the inner hasher, store the result, return it. + 4. On miss: delegate to the inner hasher, validate the result, store it, and + return it. Both ``FileHasher`` and ``CachedFileHasher`` satisfy ``FileContentHasherProtocol`` — callers do not need to know which they @@ -206,11 +203,12 @@ class CachedFileHasher: Args: file_hasher: Inner hasher that performs the actual content hashing. cacher: Cache backend implementing - ``CacherProtocol[FileHashKey, ContentHash]``. + ``CacherProtocol[FileHashKey, ContentHash]``. A backend that advertises + an algorithm must report ``"sha256"``. Raises: - ValueError: If ``file_hasher.hash_algorithm`` is not ``"sha256"``; the - message names the label given. + ValueError: If the file hasher or cacher advertises an unsupported + algorithm. """ def __init__( @@ -219,6 +217,8 @@ def __init__( cacher: "CacherProtocol[FileHashKey, ContentHash]", ) -> None: require_file_hash_algorithm(file_hasher.hash_algorithm) + for attribute in ("hash_algorithm", "algorithm"): + require_file_hash_algorithm(getattr(cacher, attribute, SHA256_ALGORITHM)) self.file_hasher = file_hasher self.cacher = cacher @@ -244,12 +244,13 @@ def hash_file(self, file_path: PathLike) -> ContentHash: hit = self.cacher.get(key) if isinstance(hit, ContentHash): try: - _ = require_storable(key.algorithm, hit.method, hit.digest) + _ = require_file_hash(key.algorithm, hit.method, hit.digest) except ValueError: pass # Custom backends can return an incompatible cached hash. else: return hit result = self.file_hasher.hash_file(file_path) + _ = require_file_hash(key.algorithm, result.method, result.digest) self.cacher.put(key, result) return result diff --git a/src/orcapod/hashing/hash_cachers.py b/src/orcapod/hashing/hash_cachers.py index 9c6f140d7..2833d58f3 100644 --- a/src/orcapod/hashing/hash_cachers.py +++ b/src/orcapod/hashing/hash_cachers.py @@ -19,10 +19,11 @@ FileHashKey, matches_stored_file_hash, parse_stored_file_hash, - require_storable, + require_file_hash, serialize_storable_file_hash, stored_hash_format, ) +from orcapod.hashing.hash_utils import SHA256_ALGORITHM, require_file_hash_algorithm from orcapod.types import ContentHash logger = logging.getLogger(__name__) @@ -87,7 +88,11 @@ def get(self, key: FileHashKey) -> ContentHash | None: Returns: Cached ``ContentHash``, or ``None`` if not found. """ - inner = self._cache.get((key.path, key.size, key.algorithm)) + try: + require_file_hash_algorithm(key.algorithm) + except ValueError: + return None + inner = self._cache.get((key.path, key.size, SHA256_ALGORITHM)) if inner is None: return None if self._match_mtime: @@ -113,7 +118,7 @@ def put(self, key: FileHashKey, value: ContentHash) -> None: (checked before the write guards), or if a write finds a different hash under the same key. """ - _ = require_storable(key.algorithm, value.method, value.digest) + _ = require_file_hash(key.algorithm, value.method, value.digest) if self._read_only: return if ( @@ -122,7 +127,7 @@ def put(self, key: FileHashKey, value: ContentHash) -> None: and key.size < self._min_cache_size_bytes ): return - entries = self._cache.setdefault((key.path, key.size, key.algorithm), {}) + entries = self._cache.setdefault((key.path, key.size, SHA256_ALGORITHM), {}) if entries.setdefault(key.mtime_ns, value) != value: raise ValueError(f"Different hash already cached for {key!r}") @@ -278,13 +283,14 @@ def get(self, key: FileHashKey) -> ContentHash | None: if self._match_mtime: row = conn.execute( "SELECT CASE WHEN typeof(hash)='blob' THEN hash END FROM file_hash_cache_v2 " - "WHERE path=? AND mtime_ns=? AND size=? AND algorithm=?", + "WHERE path=? AND mtime_ns=? AND size=? AND algorithm COLLATE BINARY=?", (str(key.path), key.mtime_ns, key.size, algorithm), ).fetchone() else: row = conn.execute( "SELECT CASE WHEN typeof(hash)='blob' THEN hash END FROM file_hash_cache_v2 " - "WHERE path=? AND size=? AND algorithm=? ORDER BY mtime_ns DESC LIMIT 1", + "WHERE path=? AND size=? AND algorithm COLLATE BINARY=? " + "ORDER BY mtime_ns DESC LIMIT 1", (str(key.path), key.size, algorithm), ).fetchone() if row is None or not isinstance(row[0], bytes): @@ -370,9 +376,12 @@ def put(self, key: FileHashKey, value: ContentHash) -> None: ) def clear(self) -> None: - """Delete all rows from the cache table.""" + """Delete SHA-256 rows, preserving rows from historical algorithms.""" conn = self._connection() - conn.execute("DELETE FROM file_hash_cache_v2") + conn.execute( + "DELETE FROM file_hash_cache_v2 WHERE algorithm COLLATE BINARY=?", + (SHA256_ALGORITHM,), + ) conn.commit() def close(self) -> None: diff --git a/src/orcapod/hashing/postgres_hash_cacher.py b/src/orcapod/hashing/postgres_hash_cacher.py index 41fb2dfe4..a5dadc456 100644 --- a/src/orcapod/hashing/postgres_hash_cacher.py +++ b/src/orcapod/hashing/postgres_hash_cacher.py @@ -19,6 +19,7 @@ serialize_storable_file_hash, stored_hash_format, ) +from orcapod.hashing.hash_utils import SHA256_ALGORITHM from orcapod.types import ContentHash logger = logging.getLogger(__name__) @@ -181,18 +182,22 @@ def get(self, key: FileHashKey) -> ContentHash | None: if hash_format is None: return None # Invalid labels can include NULs, which PostgreSQL rejects. conn = self._connection() + # Keep the index's collation for lookup and require an exact label even + # when the column uses a collation that considers different labels equal. if self._match_mtime: row = conn.execute( "SELECT hash FROM file_hash_cache_v2 " - "WHERE path=%s AND mtime_ns=%s AND size=%s AND algorithm=%s", - (str(key.path), key.mtime_ns, key.size, algorithm), + "WHERE path=%s AND mtime_ns=%s AND size=%s AND algorithm=%s " + 'AND algorithm COLLATE pg_catalog."C"=%s', + (str(key.path), key.mtime_ns, key.size, algorithm, algorithm), ).fetchone() else: row = conn.execute( "SELECT hash FROM file_hash_cache_v2 " "WHERE path=%s AND size=%s AND algorithm=%s " + 'AND algorithm COLLATE pg_catalog."C"=%s ' "ORDER BY mtime_ns DESC LIMIT 1", - (str(key.path), key.size, algorithm), + (str(key.path), key.size, algorithm, algorithm), ).fetchone() if row is None: return None @@ -284,8 +289,11 @@ def put(self, key: FileHashKey, value: ContentHash) -> None: ) def clear(self) -> None: - """Delete all rows from the cache table.""" - self._connection().execute("DELETE FROM file_hash_cache_v2") + """Delete SHA-256 rows, preserving rows from historical algorithms.""" + self._connection().execute( + 'DELETE FROM file_hash_cache_v2 WHERE algorithm COLLATE pg_catalog."C"=%s', + (SHA256_ALGORITHM,), + ) def close(self) -> None: """Close this thread's database connection.""" diff --git a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py index 35503d2c1..c0d49869c 100644 --- a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py +++ b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py @@ -30,6 +30,8 @@ from typing_extensions import override +from orcapod.hashing.file_hashers import require_file_hash +from orcapod.hashing.hash_utils import SHA256_ALGORITHM, require_file_hash_algorithm from orcapod.hashing.pandas_value_hash import ( PANDAS_DATAFRAME_HASH_LABEL, PANDAS_DATAFRAME_OPTIONS, @@ -495,10 +497,11 @@ class FileHandler: the wrapped ``UPath``, which follows symlinks by default. Args: - file_hasher: Any object with a ``hash_file(path) -> ContentHash`` method. + file_hasher: File content hasher reporting the ``sha256`` algorithm. """ def __init__(self, file_hasher: "FileContentHasherProtocol") -> None: + require_file_hash_algorithm(file_hasher.hash_algorithm) self.file_hasher = file_hasher def handle(self, obj: Any, hasher: "SemanticHasherProtocol") -> ContentHash: @@ -510,7 +513,9 @@ def handle(self, obj: Any, hasher: "SemanticHasherProtocol") -> ContentHash: raise TypeError(f"FileHandler: expected an orcapod.File, got {type(obj)!r}") wrapped = getattr(obj, "__wrapped__") logger.debug("FileHandler: hashing file content at %s", wrapped) - return self.file_hasher.hash_file(wrapped) + result = self.file_hasher.hash_file(wrapped) + _ = require_file_hash(SHA256_ALGORITHM, result.method, result.digest) + return result class DirectoryHandler: diff --git a/src/orcapod/protocols/hashing_protocols.py b/src/orcapod/protocols/hashing_protocols.py index 02272ae3b..5483036f5 100644 --- a/src/orcapod/protocols/hashing_protocols.py +++ b/src/orcapod/protocols/hashing_protocols.py @@ -144,9 +144,7 @@ class FileContentHasherProtocol(Protocol): def hash_algorithm(self) -> str: """The label of every hash ``hash_file`` returns (its ``ContentHash.method``). - A file hash cache uses it to return an entry only to a hasher of the same - algorithm (ITL-1488). To be cached (``CachedFileHasher``), the label must - be ``sha256``, the only file hash algorithm (ITL-1155). + The label must be ``sha256``, the only file hash algorithm (ITL-1155). """ ... diff --git a/tests/test_contexts/test_data_context_v1.py b/tests/test_contexts/test_data_context_v1.py index 415c545db..7df9285ff 100644 --- a/tests/test_contexts/test_data_context_v1.py +++ b/tests/test_contexts/test_data_context_v1.py @@ -12,6 +12,7 @@ from __future__ import annotations import json +import shutil from importlib import resources from pathlib import Path from typing import Any @@ -20,10 +21,13 @@ import orcapod from orcapod import contexts +from orcapod.contexts.core import ContextValidationError +from orcapod.contexts.registry import JSONDataContextRegistry from orcapod.hashing.semantic_hashing.type_handler_registry import ( PythonTypeHandlerRegistry, ) from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.types import ContentHash, PathLike from tests.test_hashing.golden import store from tests.test_hashing.golden.generate_golden_hashes import main @@ -31,6 +35,37 @@ MANIFEST_DIR = CONTEXTS_DIR / "data" +class CustomFileHasher: + """A configurable file hasher for testing manifest validation.""" + + def __init__(self, algorithm: str) -> None: + self.hash_algorithm: str = algorithm + + def hash_file(self, file_path: PathLike) -> ContentHash: + """Return a hash under the configured label.""" + _ = file_path + return ContentHash(self.hash_algorithm, b"\x00" * 16) + + +def test_context_refuses_a_custom_file_hasher_with_an_unsupported_label( + tmp_path: Path, +) -> None: + """A custom hasher declared in the manifest follows the built-in SHA-256 rule.""" + _ = shutil.copytree(MANIFEST_DIR / "schemas", tmp_path / "schemas") + spec = _manifest("v1") + spec["file_hasher"] = { + "_class": f"{__name__}.CustomFileHasher", + "_config": {"algorithm": "md5"}, + } + _ = (tmp_path / "v1.json").write_text(json.dumps(spec)) + registry = JSONDataContextRegistry(contexts_dir=tmp_path) + + with pytest.raises( + ContextValidationError, match="Unsupported file hash algorithm 'md5'" + ): + _ = registry.get_context() + + def _pins() -> dict[str, dict[str, Any]]: """The pin of each manifest, by version: ``{"manifest": ..., "releases": {...}}``, with ``"withdrawn": {...}`` when a release was withdrawn. diff --git a/tests/test_hashing/test_file_hash_cache_algorithm.py b/tests/test_hashing/test_file_hash_cache_algorithm.py index 45228dc88..e3f411de1 100644 --- a/tests/test_hashing/test_file_hash_cache_algorithm.py +++ b/tests/test_hashing/test_file_hash_cache_algorithm.py @@ -19,8 +19,10 @@ from typing_extensions import override from upath import UPath +from orcapod.hashing.directory_hashers import BasicDirectoryHasher from orcapod.hashing.file_hashers import CachedFileHasher, FileHasher, FileHashKey from orcapod.hashing.hash_cachers import InMemoryHashCacher, SqliteHashCacher +from orcapod.hashing.semantic_hashing.builtin_handlers import FileHandler from orcapod.types import ContentHash, PathLike Cacher = InMemoryHashCacher | SqliteHashCacher @@ -80,6 +82,70 @@ def test_sqlite_without_mtime_skips_a_newer_row_of_another_label( ).fetchall() == [(old_key.mtime_ns, old_blob, 1)] +def test_sqlite_clear_keeps_historical_rows(tmp_path: Path) -> None: + """Clearing the active cache leaves the old algorithm's row intact.""" + db_path = tmp_path / "cache.db" + old_key = _key("md5") + old_blob = _hash_of("md5").to_prefixed_digest() + with SqliteHashCacher(db_path) as cache: + _insert_raw(db_path, old_blob, key=old_key) + cache.put(_key("sha256"), _hash_of("sha256")) + cache.clear() + assert cache.get(_key("sha256")) is None + with sqlite3.connect(db_path) as conn: + assert conn.execute( + "SELECT algorithm, hash, cached_at FROM file_hash_cache_v2" + ).fetchall() == [("md5", old_blob, 1)] + + +@pytest.mark.parametrize("match_mtime", [True, False]) +def test_sqlite_read_and_clear_match_the_exact_label( + tmp_path: Path, match_mtime: bool +) -> None: + """A case-insensitive column cannot turn a historical row into an active one.""" + db_path = tmp_path / "cache.db" + with sqlite3.connect(db_path) as conn: + _ = conn.execute( + """CREATE TABLE file_hash_cache_v2 ( + path TEXT NOT NULL, mtime_ns INTEGER NOT NULL, size INTEGER NOT NULL, + algorithm TEXT COLLATE NOCASE NOT NULL, hash BLOB NOT NULL, + cached_at INTEGER NOT NULL, + PRIMARY KEY (path, mtime_ns, size, algorithm) + ) WITHOUT ROWID""" + ) + blob = _hash_of("sha256").to_prefixed_digest() + _insert_raw(db_path, blob, key=_key("SHA256")) + with SqliteHashCacher(db_path, match_mtime=match_mtime) as cache: + assert cache.get(_key("sha256")) is None + cache.clear() + with sqlite3.connect(db_path) as conn: + assert conn.execute( + "SELECT algorithm, hash FROM file_hash_cache_v2" + ).fetchall() == [("SHA256", blob)] + + +class _LookalikeLabel(str): + """A label that compares and hashes like SHA-256 in a dictionary.""" + + @override + def __eq__(self, other: object) -> bool: + return other == "sha256" + + @override + def __hash__(self) -> int: + return hash("sha256") + + +@pytest.mark.parametrize("match_mtime", [True, False]) +def test_memory_read_rejects_a_lookalike_label(match_mtime: bool) -> None: + """A string's underlying label determines whether a cache lookup is valid.""" + cache = InMemoryHashCacher(match_mtime=match_mtime) + value = _hash_of("sha256") + cache.put(_key("sha256"), value) + assert cache.get(_key(_LookalikeLabel("md5"))) is None + assert cache.get(_key("sha256")) == value + + @pytest.fixture def restore_file_handlers() -> Iterator[None]: """Put the default context's File and Directory handlers back afterwards.""" @@ -151,6 +217,57 @@ def put(self, key: FileHashKey, value: ContentHash) -> None: self.entries[(key.path, key.mtime_ns, key.size)] = value +class _WrongResultHasher: + """A hasher whose returned label disagrees with its advertised label.""" + + hash_algorithm: str = "sha256" + + def hash_file(self, file_path: PathLike) -> ContentHash: + """Return an incompatible hash.""" + _ = file_path + return _hash_of("md5") + + +def test_cached_file_hasher_rejects_an_invalid_computed_hash(data_file: Path) -> None: + """The wrapper validates the result even if a custom cacher accepts anything.""" + cache = _LegacyCacher() + hasher = CachedFileHasher(_WrongResultHasher(), cache) + + with pytest.raises(ValueError, match="'md5'.*'sha256'"): + _ = hasher.hash_file(data_file) + assert not cache.entries + + +def test_file_value_rejects_an_invalid_computed_hash(data_file: Path) -> None: + """The uncached File handler also checks hashes returned by custom hashers.""" + from orcapod.contexts import get_default_semantic_hasher + from orcapod.logical_types.file_type import File + + handler = FileHandler(_WrongResultHasher()) + with pytest.raises(ValueError, match="'md5'.*'sha256'"): + _ = handler.handle(File(data_file), get_default_semantic_hasher()) + + +def test_directory_rejects_an_invalid_file_leaf_hash(data_file: Path) -> None: + """A custom file hasher must produce SHA-256 before a leaf is folded in.""" + hasher = BasicDirectoryHasher(_WrongResultHasher()) + + with pytest.raises(ValueError, match="'md5'.*'sha256'"): + _ = hasher.hash_directory(data_file.parent) + + +class _LabelledCacher(_LegacyCacher): + """A custom cacher that advertises an algorithm.""" + + hash_algorithm: str = "md5" + + +def test_cached_file_hasher_refuses_a_custom_cachers_unsupported_label() -> None: + """An explicit cacher algorithm follows the same rule as the inner hasher.""" + with pytest.raises(ValueError, match="Unsupported file hash algorithm 'md5'"): + _ = CachedFileHasher(FileHasher(), _LabelledCacher()) + + @pytest.mark.parametrize( "cached_value", [ @@ -564,3 +681,14 @@ def test_cached_file_hasher_refuses_a_label_no_cache_can_store(cacher: Cacher): with pytest.raises(ValueError, match="app-sha256-v1"): _ = CachedFileHasher(inner, cacher) assert inner.calls == 0 + + +@pytest.mark.parametrize("consumer", [FileHandler, BasicDirectoryHasher]) +def test_uncached_consumers_refuse_an_unsupported_file_hasher( + consumer: type[FileHandler] | type[BasicDirectoryHasher], +) -> None: + """Direct injection into File and Directory follows the context's SHA-256 rule.""" + inner = _CustomLabelHasher() + with pytest.raises(ValueError, match="Unsupported file hash algorithm"): + _ = consumer(inner) + assert inner.calls == 0 diff --git a/tests/test_hashing/test_postgres_hash_cacher.py b/tests/test_hashing/test_postgres_hash_cacher.py index 1ace268fb..6d117780d 100644 --- a/tests/test_hashing/test_postgres_hash_cacher.py +++ b/tests/test_hashing/test_postgres_hash_cacher.py @@ -788,6 +788,17 @@ def _all_rows(pg_conninfo: str) -> list[tuple[object, ...]]: @pytest.mark.postgres class TestPostgresHashCacherAlgorithmLabel: + def test_clear_keeps_historical_rows(self, pg_conninfo: str) -> None: + """Clearing the active cache leaves the old algorithm's row intact.""" + old_key = _key_for_algorithm("md5") + _insert_raw(pg_conninfo, old_key, b"md5:" + b"\x07" * 16) + before = _all_rows(pg_conninfo) + with PostgresHashCacher(pg_conninfo) as cache: + cache.put(make_key(), make_hash()) + cache.clear() + assert cache.get(make_key()) is None + assert _all_rows(pg_conninfo) == before + @pytest.mark.parametrize("match_mtime", [True, False]) def test_row_of_another_algorithm_stays_and_is_never_read( self, pg_conninfo: str, match_mtime: bool @@ -857,7 +868,7 @@ def test_rejects_a_conflict_from_another_label( # A stray row whose label the collation equates with the key's label. key = make_key() stray = FileHashKey(key.path, key.mtime_ns, key.size, "SHA256") - blob = b"SHA256:" + b"\x07" * 32 + blob = b"sha256:" + b"\x07" * 32 _insert_raw(pg_conninfo, stray, blob) with PostgresHashCacher(pg_conninfo, match_mtime=match_mtime) as cache: assert cache.get(key) is None @@ -867,6 +878,7 @@ def test_rejects_a_conflict_from_another_label( with pytest.raises(ValueError, match="'SHA256'.*sha256 is the only"): cache.put(stray, ContentHash("SHA256", b"\x02" * 32)) assert cache.get(stray) is None + cache.clear() with connect(pg_conninfo) as conn: assert conn.execute( "SELECT convert_to(algorithm, 'UTF8'), hash, cached_at FROM file_hash_cache_v2" From 694e97cdc4b55c47fd04c1a1929d6166545b5b53 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 02:30:32 -0800 Subject: [PATCH 4/8] fix(hashing): enforce canonical SHA-256 at custom hash boundaries --- changelog.d/ITL-1155.md | 7 + docs/dev/design_issues/ITL-1155-FH1.md | 6 +- docs/reference/hashing.md | 2 +- src/orcapod/contexts/registry.py | 20 ++- src/orcapod/hashing/directory_hashers.py | 44 +++--- src/orcapod/hashing/file_hashers.py | 86 ++++++------ src/orcapod/hashing/hash_cachers.py | 4 +- .../semantic_hashing/builtin_handlers.py | 6 +- tests/test_contexts/test_data_context_v1.py | 35 +++++ .../test_file_hash_cache_algorithm.py | 125 ++++++++++++++++++ tests/test_hashing/test_hash_label_rule.py | 6 + 11 files changed, 277 insertions(+), 64 deletions(-) diff --git a/changelog.d/ITL-1155.md b/changelog.d/ITL-1155.md index a3a3de9bb..d3f54f450 100644 --- a/changelog.d/ITL-1155.md +++ b/changelog.d/ITL-1155.md @@ -11,3 +11,10 @@ layout and historical rows. Reads for other algorithms miss and writes raise an error. Clearing a persistent cache deletes only its `sha256` rows. SHA-256 digests and their `sha256` label are unchanged. + +### Fixed + +- Serialize custom file hashes from their validated SHA-256 label and digest + when returning them, caching them, or folding them into a directory hash. + Reject unsupported algorithm settings before consulting a custom file cache + and when configuring a directory hasher. diff --git a/docs/dev/design_issues/ITL-1155-FH1.md b/docs/dev/design_issues/ITL-1155-FH1.md index 066449d9b..69a38e346 100644 --- a/docs/dev/design_issues/ITL-1155-FH1.md +++ b/docs/dev/design_issues/ITL-1155-FH1.md @@ -11,7 +11,9 @@ procedure that produced it. **Fix:** Use SHA-256 over the file bytes and keep the `sha256` label. Reject other algorithms in built-in and custom file hashers and cache writes. Verify -computed file hashes before returning, caching, or folding them into a directory -hash. Cache reads for other labels miss, and clearing a persistent cache +computed file hashes and serialize them using their validated label and digest +before returning, caching, or folding them into a directory hash. Reject +unsupported algorithms before invoking a custom cache or configuring a directory +hasher. Direct cache reads for other labels miss, and clearing a persistent cache preserves historical rows. Remove the algorithm selection from cache warming and drop the `xxhash` dependency. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index a83c9eea9..faed87d11 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -317,7 +317,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. |---|---|---|---|---| | structure hasher | a Python value as a tagged JSON tree | SHA-256 of canonical JSON, `semantic_v1` | every `content_hash()` / `pipeline_hash()`, type and function hash; the names built on schema hashes | `hashing/semantic_hashing/semantic_hasher.py:SemanticAwarePythonHasher._hash_to_content_hash` | | Arrow hasher | a table after the semantic visitor | starfix, `arrow_v1` (a table Orcapod built: float rule on); `hash_table_strict`: `arrow_strict_v1` (a pyarrow table given as a value: every bit counts); `hash_table_ordered`: `arrow_ordered_v1` (a library value's digest: every bit counts); `hash_schema`: `arrow_schema_v1` | row data hashes, entry ids, row keys, default source ids, table values; every schema in an identity | `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_strict`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_ordered`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_schema`, `hashing/arrow_hashers.py:StarfixArrowHasher._digest`, `hashing/starfix_digest.py:_digest_table`, `hashing/starfix_digest.py:digest_schema` | -| file hasher | a file's bytes | SHA-256 of the bytes, label `sha256`. Hashers, cache writes, and data context loading reject other algorithms. Cache lookups for other labels miss (ITL-1155). | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put` | +| file hasher | a file's bytes | SHA-256 of the bytes, label `sha256`. Hashers, cache writes, and data context loading reject other algorithms. Direct cache lookups for other labels miss (ITL-1155). Custom file hashes use the validated SHA-256 fields for serialization. | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/semantic_hashing/builtin_handlers.py:FileHandler.handle`, `hashing/file_hashers.py:canonical_file_hash`, `hashing/file_hashers.py:_validated_file_digest`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put` | | directory hasher | a directory tree | Merkle tree of SHA-256 entries, `directory_v1`; file leaves taken with their label | `Directory` value hash | `hashing/directory_hashers.py:BasicDirectoryHasher.hash_directory`, `hashing/directory_hashers.py:_hash_dir` | | array value hash | an array: element digest, then order, byte order, struct layout | SHA-256, `ndarray_v1` (the element digest is a step of the same algorithm) | `numpy.ndarray` value hash | `logical_types/numpy_type.py:array_value_digest`, `logical_types/array_format.py:array_digest_v1` | | tensor value hash | element digest, flags, strides, class | SHA-256, `torch_tensor_v1` | `torch.Tensor` value hash | `logical_types/torch_type.py:tensor_digest` | diff --git a/src/orcapod/contexts/registry.py b/src/orcapod/contexts/registry.py index 8466d54f8..8022d1419 100644 --- a/src/orcapod/contexts/registry.py +++ b/src/orcapod/contexts/registry.py @@ -414,7 +414,11 @@ def _create_context_from_spec(self, spec: dict[str, Any]) -> DataContext: instantiated automatically and become available as ``_ref`` targets for later components in the same file. """ - from orcapod.hashing.hash_utils import require_file_hash_algorithm + from orcapod.hashing.directory_hashers import require_directory_hash_algorithm + from orcapod.hashing.hash_utils import ( + SHA256_ALGORITHM, + require_file_hash_algorithm, + ) try: context_key = spec["context_key"] @@ -462,11 +466,25 @@ def _create_context_from_spec(self, spec: dict[str, Any]) -> DataContext: continue if isinstance(value, dict) and "_class" in value: logger.debug(f"Creating {key} for context {version}") + if key == "directory_hasher": + config = value.get("_config", {}) + if isinstance(config, dict) and "algorithm" in config: + require_directory_hash_algorithm( + parse_objectspec(config["algorithm"], ref_lut=ref_lut) + ) + value = { + **value, + "_config": {**config, "algorithm": SHA256_ALGORITHM}, + } component = parse_objectspec(value, ref_lut=ref_lut) if key == "file_hasher": require_file_hash_algorithm( getattr(component, "hash_algorithm", None) ) + elif key == "directory_hasher": + require_directory_hash_algorithm( + getattr(component, "algorithm", SHA256_ALGORITHM) + ) ref_lut[key] = component # The value handlers of the logical types join the core handlers of the diff --git a/src/orcapod/hashing/directory_hashers.py b/src/orcapod/hashing/directory_hashers.py index 985c1e4c4..a35740cea 100644 --- a/src/orcapod/hashing/directory_hashers.py +++ b/src/orcapod/hashing/directory_hashers.py @@ -10,7 +10,7 @@ from upath import UPath -from orcapod.hashing.file_hashers import require_file_hash +from orcapod.hashing.file_hashers import canonical_file_hash from orcapod.hashing.hash_utils import SHA256_ALGORITHM, require_file_hash_algorithm from orcapod.protocols.hashing_protocols import FileContentHasherProtocol from orcapod.types import ContentHash, PathLike @@ -28,6 +28,15 @@ """ +def require_directory_hash_algorithm(algorithm: object) -> None: + """Require SHA-256 for the entry and node digests of ``directory_v1``.""" + if str.__eq__(SHA256_ALGORITHM, algorithm) is not True: + raise ValueError( + f"{DIRECTORY_HASH_LABEL} is defined over {SHA256_ALGORITHM} " + f"entry and node digests; got algorithm {algorithm!r}" + ) + + def _compile_ignore( ignore: Callable[[UPath], bool] | Iterable[str] | None, ) -> Callable[[UPath], bool] | None: @@ -66,7 +75,6 @@ def _hash_dir( path: UPath, root: UPath, filter_fn: Callable[[UPath], bool] | None, - algorithm: str, file_hasher: FileContentHasherProtocol, ) -> bytes: """Recursively compute the Merkle hash of a directory. @@ -79,7 +87,6 @@ def _hash_dir( ``root`` and returns ``True`` to exclude the entry. Excluding a directory entry also implicitly excludes its entire subtree (the recursive call is skipped for excluded directories). - algorithm: Hash algorithm name used for structural (entry and node) hashing. file_hasher: Hasher used to compute ``ContentHash`` for each file leaf. Returns: @@ -105,26 +112,26 @@ def _hash_dir( entry_bytes = b"symlink\x00" + name_bytes + b"\x00" + target.encode("utf-8") elif child.is_file(): file_hash = file_hasher.hash_file(child) - _ = require_file_hash(SHA256_ALGORITHM, file_hash.method, file_hash.digest) + canonical_hash = canonical_file_hash(SHA256_ALGORITHM, file_hash) # The file hash comes from another hasher: it enters with its label. entry_bytes = ( - b"file\x00" + name_bytes + b"\x00" + file_hash.to_prefixed_digest() + b"file\x00" + name_bytes + b"\x00" + canonical_hash.to_prefixed_digest() ) elif child.is_dir(): - subdir_digest = _hash_dir(child, root, filter_fn, algorithm, file_hasher) + subdir_digest = _hash_dir(child, root, filter_fn, file_hasher) entry_bytes = b"dir\x00" + name_bytes + b"\x00" + subdir_digest else: # Special file (socket, device node, named pipe) — skip silently. logger.debug("BasicDirectoryHasher: skipping special file %s", child) continue - entry_digest = hashlib.new(algorithm, entry_bytes).digest() + entry_digest = hashlib.sha256(entry_bytes).digest() entries.append((name_bytes, entry_digest)) # Sort byte-wise by name — locale-independent, deterministic. entries.sort(key=lambda x: x[0]) - h = hashlib.new(algorithm) + h = hashlib.sha256() h.update(b"directory\x00") for _, entry_digest in entries: h.update(entry_digest) @@ -169,16 +176,20 @@ def __init__( algorithm: str = SHA256_ALGORITHM, buffer_size: int = 65536, ) -> None: - if str.__eq__(SHA256_ALGORITHM, algorithm) is not True: - raise ValueError( - f"{DIRECTORY_HASH_LABEL} is defined over {SHA256_ALGORITHM} " - f"entry and node digests; got algorithm {algorithm!r}" - ) + self.algorithm = algorithm require_file_hash_algorithm(file_hasher.hash_algorithm) self.file_hasher = file_hasher - self.algorithm = SHA256_ALGORITHM self.buffer_size = buffer_size + @property + def algorithm(self) -> str: + """The directory hasher's structural algorithm, SHA-256.""" + return SHA256_ALGORITHM + + @algorithm.setter + def algorithm(self, value: str) -> None: + require_directory_hash_algorithm(value) + def hash_directory( self, directory_path: PathLike, @@ -206,6 +217,8 @@ def hash_directory( A ``ContentHash`` with ``method="directory_v1"`` (``DIRECTORY_HASH_LABEL``). Raises: + ValueError: If the file hasher advertises an unsupported algorithm or + returns a hash with an invalid label or digest size. FileNotFoundError: If ``directory_path`` does not exist. NotADirectoryError: If ``directory_path`` is not a directory. PermissionError: If the directory is not traversable. @@ -223,7 +236,8 @@ def hash_directory( >>> # Custom callable filter (receives relative UPath from root) >>> result = hasher.hash_directory("/tmp/mydir", ignore=lambda p: p.name.startswith(".")) """ + require_file_hash_algorithm(self.file_hasher.hash_algorithm) path = UPath(directory_path) filter_fn = _compile_ignore(ignore) - digest = _hash_dir(path, path, filter_fn, self.algorithm, self.file_hasher) + digest = _hash_dir(path, path, filter_fn, self.file_hasher) return ContentHash(method=DIRECTORY_HASH_LABEL, digest=digest) diff --git a/src/orcapod/hashing/file_hashers.py b/src/orcapod/hashing/file_hashers.py index 2dbe5bcdd..35fcfab4d 100644 --- a/src/orcapod/hashing/file_hashers.py +++ b/src/orcapod/hashing/file_hashers.py @@ -54,42 +54,41 @@ def stored_hash_format(label: str) -> tuple[bytes, int] | None: return label.encode("ascii") + b":", digest_size -def require_file_hash(algorithm: str, method: str, digest: bytes) -> int: - """Require a file hash of the expected algorithm and return its digest size. - - The value's label must match the expected algorithm, and its digest must be - exactly that algorithm's length. - - Args: - algorithm: The expected algorithm label. - method: The incoming hash's algorithm label. - digest: The incoming hash's raw digest. - - Returns: - The validated digest size. - - Raises: - ValueError: If the labels differ, the label is not ``sha256`` (the only - file hash algorithm), or the digest has another length. - """ +def _validated_file_digest(algorithm: str, value: ContentHash) -> bytes: + """Snapshot the raw digest after checking the hash's label and digest size.""" + method = value.method if str.__eq__(algorithm, method) is not True: raise ValueError(f"File hash has label {method!r}, expected {algorithm!r}") size = file_hash_digest_size(algorithm) + # Validate the same bytes that will be returned, even for a custom hash. + raw_digest = value.digest + digest = ( + raw_digest if type(raw_digest) is bytes else memoryview(raw_digest).tobytes() + ) if len(digest) != size: raise ValueError(f"A {algorithm!r} digest is {size} bytes, not {len(digest)}") - return size + return digest + + +def canonical_file_hash(algorithm: str, value: ContentHash) -> ContentHash: + """Validate the file hash and ensure it uses canonical SHA-256 serialization.""" + digest = _validated_file_digest(algorithm, value) + if ( + type(value) is ContentHash + and type(value.method) is str + and value.digest is digest + ): + return value + return ContentHash(SHA256_ALGORITHM, digest) def serialize_storable_file_hash( algorithm: str, value: ContentHash ) -> tuple[bytes, int, bytes]: """Return the key's prefix and digest size, and the canonical bytes to store.""" - # Snapshot the raw buffer so validation and serialization use the same bytes, - # even if a subclass overrides digest access or bytes operations. - digest = memoryview(value.digest).tobytes() - digest_size = require_file_hash(algorithm, value.method, digest) - prefix = algorithm.encode("ascii") + b":" - return prefix, digest_size, prefix + digest + digest = _validated_file_digest(algorithm, value) + prefix = SHA256_ALGORITHM.encode("ascii") + b":" + return prefix, len(digest), prefix + digest def matches_stored_file_hash(blob: object, prefix: bytes, digest_size: int) -> bool: @@ -185,13 +184,14 @@ class CachedFileHasher: ``CacherProtocol[FileHashKey, ContentHash]``. On each call to ``hash_file``: - 1. Resolve the path to an absolute ``UPath`` and stat the file. - 2. Look up ``(path, mtime_ns, size, algorithm)`` in the cacher, using - the inner hasher's ``hash_algorithm``. Each algorithm has its own entry. + 1. Validate the advertised algorithms, resolve the path to an absolute + ``UPath``, and stat the file. + 2. Look up ``(path, mtime_ns, size, algorithm)`` in the cacher using the + canonical SHA-256 label. 3. Accept a hit only if it is a ``ContentHash`` with the expected label and digest length. - 4. On miss: delegate to the inner hasher, validate the result, store it, and - return it. + 4. On miss: delegate to the inner hasher, validate the result, and cache it. + Both hits and newly computed results return a canonical ``ContentHash``. Both ``FileHasher`` and ``CachedFileHasher`` satisfy ``FileContentHasherProtocol`` — callers do not need to know which they @@ -216,11 +216,17 @@ def __init__( file_hasher: FileContentHasherProtocol, cacher: "CacherProtocol[FileHashKey, ContentHash]", ) -> None: - require_file_hash_algorithm(file_hasher.hash_algorithm) - for attribute in ("hash_algorithm", "algorithm"): - require_file_hash_algorithm(getattr(cacher, attribute, SHA256_ALGORITHM)) self.file_hasher = file_hasher self.cacher = cacher + self._validate_algorithms() + + def _validate_algorithms(self) -> None: + """Refuse unsupported labels before hashing or consulting the cache.""" + require_file_hash_algorithm(self.hash_algorithm) + for attribute in ("hash_algorithm", "algorithm"): + require_file_hash_algorithm( + getattr(self.cacher, attribute, SHA256_ALGORITHM) + ) @property def hash_algorithm(self) -> str: @@ -236,21 +242,21 @@ def hash_file(self, file_path: PathLike) -> ContentHash: Returns: ContentHash of the file's content (from cache or computed). """ + self._validate_algorithms() path = file_path if isinstance(file_path, UPath) else UPath(file_path) path = path.resolve() stat = path.stat() - key = FileHashKey(path, stat.st_mtime_ns, stat.st_size, self.hash_algorithm) + key = FileHashKey(path, stat.st_mtime_ns, stat.st_size, SHA256_ALGORITHM) hit = self.cacher.get(key) if isinstance(hit, ContentHash): try: - _ = require_file_hash(key.algorithm, hit.method, hit.digest) - except ValueError: + return canonical_file_hash(key.algorithm, hit) + except (TypeError, ValueError): pass # Custom backends can return an incompatible cached hash. - else: - return hit - result = self.file_hasher.hash_file(file_path) - _ = require_file_hash(key.algorithm, result.method, result.digest) + result = canonical_file_hash( + key.algorithm, self.file_hasher.hash_file(file_path) + ) self.cacher.put(key, result) return result diff --git a/src/orcapod/hashing/hash_cachers.py b/src/orcapod/hashing/hash_cachers.py index 2833d58f3..b2810c255 100644 --- a/src/orcapod/hashing/hash_cachers.py +++ b/src/orcapod/hashing/hash_cachers.py @@ -17,9 +17,9 @@ from orcapod.hashing.file_hashers import ( FILE_HASH_CACHE_SCHEMA_VERSION, FileHashKey, + canonical_file_hash, matches_stored_file_hash, parse_stored_file_hash, - require_file_hash, serialize_storable_file_hash, stored_hash_format, ) @@ -118,7 +118,7 @@ def put(self, key: FileHashKey, value: ContentHash) -> None: (checked before the write guards), or if a write finds a different hash under the same key. """ - _ = require_file_hash(key.algorithm, value.method, value.digest) + value = canonical_file_hash(key.algorithm, value) if self._read_only: return if ( diff --git a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py index c0d49869c..f0ffa9dc7 100644 --- a/src/orcapod/hashing/semantic_hashing/builtin_handlers.py +++ b/src/orcapod/hashing/semantic_hashing/builtin_handlers.py @@ -30,7 +30,7 @@ from typing_extensions import override -from orcapod.hashing.file_hashers import require_file_hash +from orcapod.hashing.file_hashers import canonical_file_hash from orcapod.hashing.hash_utils import SHA256_ALGORITHM, require_file_hash_algorithm from orcapod.hashing.pandas_value_hash import ( PANDAS_DATAFRAME_HASH_LABEL, @@ -511,11 +511,11 @@ def handle(self, obj: Any, hasher: "SemanticHasherProtocol") -> ContentHash: if not isinstance(obj, File): raise TypeError(f"FileHandler: expected an orcapod.File, got {type(obj)!r}") + require_file_hash_algorithm(self.file_hasher.hash_algorithm) wrapped = getattr(obj, "__wrapped__") logger.debug("FileHandler: hashing file content at %s", wrapped) result = self.file_hasher.hash_file(wrapped) - _ = require_file_hash(SHA256_ALGORITHM, result.method, result.digest) - return result + return canonical_file_hash(SHA256_ALGORITHM, result) class DirectoryHandler: diff --git a/tests/test_contexts/test_data_context_v1.py b/tests/test_contexts/test_data_context_v1.py index 7df9285ff..5f1eb0874 100644 --- a/tests/test_contexts/test_data_context_v1.py +++ b/tests/test_contexts/test_data_context_v1.py @@ -66,6 +66,41 @@ def test_context_refuses_a_custom_file_hasher_with_an_unsupported_label( _ = registry.get_context() +class CustomDirectoryHasher: + """A custom directory hasher that accepts any algorithm setting.""" + + def __init__(self, algorithm: str = "md5", *, report_algorithm: bool) -> None: + if report_algorithm: + self.algorithm: str = algorithm + + def hash_directory( + self, directory_path: PathLike, ignore: object = None + ) -> ContentHash: + """Stand in for an implementation using the configured algorithm.""" + return ContentHash("md5", b"\x00" * 16) + + +@pytest.mark.parametrize( + "config", + [{"algorithm": "md5", "report_algorithm": False}, {"report_algorithm": True}], + ids=["declared", "advertised"], +) +def test_context_refuses_a_custom_directory_hasher_with_an_unsupported_algorithm( + tmp_path: Path, config: dict[str, Any] +) -> None: + _ = shutil.copytree(MANIFEST_DIR / "schemas", tmp_path / "schemas") + spec = _manifest("v1") + spec["directory_hasher"] = { + "_class": f"{__name__}.CustomDirectoryHasher", + "_config": config, + } + _ = (tmp_path / "v1.json").write_text(json.dumps(spec)) + registry = JSONDataContextRegistry(contexts_dir=tmp_path) + + with pytest.raises(ContextValidationError, match="directory_v1.*sha256.*'md5'"): + _ = registry.get_context() + + def _pins() -> dict[str, dict[str, Any]]: """The pin of each manifest, by version: ``{"manifest": ..., "releases": {...}}``, with ``"withdrawn": {...}`` when a release was withdrawn. diff --git a/tests/test_hashing/test_file_hash_cache_algorithm.py b/tests/test_hashing/test_file_hash_cache_algorithm.py index e3f411de1..127bd8116 100644 --- a/tests/test_hashing/test_file_hash_cache_algorithm.py +++ b/tests/test_hashing/test_file_hash_cache_algorithm.py @@ -228,6 +228,100 @@ def hash_file(self, file_path: PathLike) -> ContentHash: return _hash_of("md5") +class _MisencodedFileHash(ContentHash): + @override + def to_prefixed_digest(self) -> bytes: + return b"md5:" + b"\x07" * 16 + + +class _MisencodingFileHasher: + hash_algorithm: str = "sha256" + + def hash_file(self, file_path: PathLike) -> ContentHash: + digest = FileHasher().hash_file(file_path).digest + return _MisencodedFileHash(self.hash_algorithm, digest) + + +def test_cached_file_hasher_canonicalizes_custom_results(data_file: Path) -> None: + cache = _LegacyCacher() + hasher = CachedFileHasher(_MisencodingFileHasher(), cache) + expected = FileHasher().hash_file(data_file).to_prefixed_digest() + + assert hasher.hash_file(data_file).to_prefixed_digest() == expected + (stored,) = cache.entries.values() + assert isinstance(stored, ContentHash) + assert stored.to_prefixed_digest() == expected + + +def test_cached_file_hasher_canonicalizes_custom_hits(data_file: Path) -> None: + cache = _LegacyCacher() + hasher = _CountingHasher() + path = UPath(data_file.resolve()) + stat = path.stat() + value = _MisencodingFileHasher().hash_file(data_file) + cache.put(FileHashKey(path, stat.st_mtime_ns, stat.st_size, "sha256"), value) + + result = CachedFileHasher(hasher, cache).hash_file(data_file) + + assert ( + result.to_prefixed_digest() + == FileHasher().hash_file(data_file).to_prefixed_digest() + ) + assert hasher.reads == 0 + + +def test_file_value_canonicalizes_custom_results(data_file: Path) -> None: + from orcapod.contexts import get_default_semantic_hasher + from orcapod.logical_types.file_type import File + + handler = FileHandler(_MisencodingFileHasher()) + result = handler.handle(File(data_file), get_default_semantic_hasher()) + assert ( + result.to_prefixed_digest() + == FileHasher().hash_file(data_file).to_prefixed_digest() + ) + + +def test_directory_canonicalizes_custom_file_leaves(data_file: Path) -> None: + plain = BasicDirectoryHasher(FileHasher()) + custom = BasicDirectoryHasher(_MisencodingFileHasher()) + assert custom.hash_directory(data_file.parent) == plain.hash_directory( + data_file.parent + ) + + +def test_memory_cacher_canonicalizes_custom_values() -> None: + key = _key("sha256") + expected = _hash_of("sha256") + cache = InMemoryHashCacher() + cache.put(key, _MisencodedFileHash(expected.method, expected.digest)) + + result = cache.get(key) + assert result is not None + assert result.to_prefixed_digest() == expected.to_prefixed_digest() + + +@pytest.mark.parametrize("consumer", ["file", "directory"]) +def test_uncached_consumers_refuse_a_changed_label_before_hashing( + data_file: Path, consumer: str +) -> None: + from orcapod.contexts import get_default_semantic_hasher + from orcapod.logical_types.file_type import File + + inner = _CountingHasher() + if consumer == "file": + file_handler = FileHandler(inner) + inner.inner.algorithm = "md5" + with pytest.raises(ValueError, match="Unsupported file hash algorithm 'md5'"): + _ = file_handler.handle(File(data_file), get_default_semantic_hasher()) + else: + directory_hasher = BasicDirectoryHasher(inner) + inner.inner.algorithm = "md5" + with pytest.raises(ValueError, match="Unsupported file hash algorithm 'md5'"): + _ = directory_hasher.hash_directory(data_file.parent) + assert inner.reads == 0 + + def test_cached_file_hasher_rejects_an_invalid_computed_hash(data_file: Path) -> None: """The wrapper validates the result even if a custom cacher accepts anything.""" cache = _LegacyCacher() @@ -268,6 +362,37 @@ def test_cached_file_hasher_refuses_a_custom_cachers_unsupported_label() -> None _ = CachedFileHasher(FileHasher(), _LabelledCacher()) +@pytest.mark.parametrize("changed_component", ["hasher", "cacher"]) +def test_cached_file_hasher_refuses_changed_labels_before_cache_lookup( + data_file: Path, changed_component: str +) -> None: + class TrackingCacher(_LabelledCacher): + hash_algorithm: str = "sha256" + + def __init__(self) -> None: + super().__init__() + self.lookups: list[str] = [] + + @override + def get(self, key: FileHashKey) -> ContentHash | None: + self.lookups.append(key.algorithm) + return _hash_of("md5") + + inner = _WrongResultHasher() + cache = TrackingCacher() + wrapped = CachedFileHasher(inner, cache) + changed = inner if changed_component == "hasher" else cache + changed.hash_algorithm = "md5" + + with pytest.raises(ValueError) as raised: + _ = wrapped.hash_file(data_file) + assert not cache.lookups + assert not cache.entries + assert str(raised.value) == ( + "Unsupported file hash algorithm 'md5': sha256 is the only file hash algorithm" + ) + + @pytest.mark.parametrize( "cached_value", [ diff --git a/tests/test_hashing/test_hash_label_rule.py b/tests/test_hashing/test_hash_label_rule.py index fc20d7449..f6eb49003 100644 --- a/tests/test_hashing/test_hash_label_rule.py +++ b/tests/test_hashing/test_hash_label_rule.py @@ -187,6 +187,12 @@ def test_directory_label_names_the_sha256_procedure_only(self) -> None: file_hasher=FileHasher(), algorithm="md5" ) + def test_directory_algorithm_cannot_be_reassigned_to_md5(self) -> None: + hasher = directory_hashers.BasicDirectoryHasher(file_hasher=FileHasher()) + with pytest.raises(ValueError, match="sha256.*'md5'"): + hasher.algorithm = "md5" + assert hasher.algorithm == "sha256" + # --------------------------------------------------------------------------- # Rule 1 (ITL-1154): a hash fed into another hash carries its label From 6745c14c450940ffb2111230e045e0cbcc643e5f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 03:01:04 -0800 Subject: [PATCH 5/8] fix(hashing): enforce SHA-256 at directory hashing boundaries --- changelog.d/ITL-1155.md | 3 +- docs/dev/design_issues/ITL-1155-FH1.md | 9 +-- docs/reference/hashing.md | 6 +- src/orcapod/hashing/directory_hashers.py | 26 ++++++- src/orcapod/hashing/file_hashers.py | 6 +- src/orcapod/hashing/hash_cachers.py | 6 +- src/orcapod/hashing/postgres_hash_cacher.py | 6 +- .../semantic_hashing/builtin_handlers.py | 20 ++++-- src/orcapod/protocols/hashing_protocols.py | 9 ++- tests/test_contexts/test_data_context_v1.py | 27 +++++++ tests/test_hashing/test_directory_handler.py | 71 ++++++++++++++++++- .../test_file_hash_cache_algorithm.py | 37 ++++++++++ .../test_hashing/test_hash_site_inventory.py | 56 +++++++++++++++ 13 files changed, 254 insertions(+), 28 deletions(-) diff --git a/changelog.d/ITL-1155.md b/changelog.d/ITL-1155.md index d3f54f450..c89895d56 100644 --- a/changelog.d/ITL-1155.md +++ b/changelog.d/ITL-1155.md @@ -17,4 +17,5 @@ - Serialize custom file hashes from their validated SHA-256 label and digest when returning them, caching them, or folding them into a directory hash. Reject unsupported algorithm settings before consulting a custom file cache - and when configuring a directory hasher. + or invoking a custom file or directory hasher. Validate custom directory + results against the `directory_v1` format. diff --git a/docs/dev/design_issues/ITL-1155-FH1.md b/docs/dev/design_issues/ITL-1155-FH1.md index 69a38e346..bd631fd4b 100644 --- a/docs/dev/design_issues/ITL-1155-FH1.md +++ b/docs/dev/design_issues/ITL-1155-FH1.md @@ -13,7 +13,8 @@ procedure that produced it. other algorithms in built-in and custom file hashers and cache writes. Verify computed file hashes and serialize them using their validated label and digest before returning, caching, or folding them into a directory hash. Reject -unsupported algorithms before invoking a custom cache or configuring a directory -hasher. Direct cache reads for other labels miss, and clearing a persistent cache -preserves historical rows. Remove the algorithm selection from cache warming and -drop the `xxhash` dependency. +unsupported algorithms before invoking a custom cache or using a custom file or +directory hasher. Validate directory results against the `directory_v1` label +and SHA-256 digest width. Direct cache reads for other labels miss, and clearing +a persistent cache preserves historical rows. Remove the algorithm selection +from cache warming and drop the `xxhash` dependency. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index faed87d11..e0f84f0d8 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -317,8 +317,8 @@ test session with `-p tests.test_hashing.hash_site_trace`. |---|---|---|---|---| | structure hasher | a Python value as a tagged JSON tree | SHA-256 of canonical JSON, `semantic_v1` | every `content_hash()` / `pipeline_hash()`, type and function hash; the names built on schema hashes | `hashing/semantic_hashing/semantic_hasher.py:SemanticAwarePythonHasher._hash_to_content_hash` | | Arrow hasher | a table after the semantic visitor | starfix, `arrow_v1` (a table Orcapod built: float rule on); `hash_table_strict`: `arrow_strict_v1` (a pyarrow table given as a value: every bit counts); `hash_table_ordered`: `arrow_ordered_v1` (a library value's digest: every bit counts); `hash_schema`: `arrow_schema_v1` | row data hashes, entry ids, row keys, default source ids, table values; every schema in an identity | `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_strict`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_ordered`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_schema`, `hashing/arrow_hashers.py:StarfixArrowHasher._digest`, `hashing/starfix_digest.py:_digest_table`, `hashing/starfix_digest.py:digest_schema` | -| file hasher | a file's bytes | SHA-256 of the bytes, label `sha256`. Hashers, cache writes, and data context loading reject other algorithms. Direct cache lookups for other labels miss (ITL-1155). Custom file hashes use the validated SHA-256 fields for serialization. | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/semantic_hashing/builtin_handlers.py:FileHandler.handle`, `hashing/file_hashers.py:canonical_file_hash`, `hashing/file_hashers.py:_validated_file_digest`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put` | -| directory hasher | a directory tree | Merkle tree of SHA-256 entries, `directory_v1`; file leaves taken with their label | `Directory` value hash | `hashing/directory_hashers.py:BasicDirectoryHasher.hash_directory`, `hashing/directory_hashers.py:_hash_dir` | +| file hasher | a file's bytes | SHA-256 of the bytes, label `sha256`. Hashers, cache writes, and data context loading reject other algorithms. Direct cache lookups for other labels miss (ITL-1155). Custom file hashes use the validated SHA-256 fields for serialization. | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/semantic_hashing/builtin_handlers.py:FileHandler.handle`, `hashing/file_hashers.py:canonical_file_hash`, `hashing/file_hashers.py:_validated_file_digest`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put`, `hashing/postgres_hash_cacher.py:PostgresHashCacher.get`, `hashing/postgres_hash_cacher.py:PostgresHashCacher.put` | +| directory hasher | a directory tree | Merkle tree of SHA-256 entries, `directory_v1`; file leaves taken with their label. The handler requires SHA-256 at use and validates the returned `directory_v1` hash. | `Directory` value hash | `hashing/directory_hashers.py:BasicDirectoryHasher.hash_directory`, `hashing/directory_hashers.py:_hash_dir`, `hashing/semantic_hashing/builtin_handlers.py:DirectoryHandler.handle`, `hashing/directory_hashers.py:canonical_directory_hash` | | array value hash | an array: element digest, then order, byte order, struct layout | SHA-256, `ndarray_v1` (the element digest is a step of the same algorithm) | `numpy.ndarray` value hash | `logical_types/numpy_type.py:array_value_digest`, `logical_types/array_format.py:array_digest_v1` | | tensor value hash | element digest, flags, strides, class | SHA-256, `torch_tensor_v1` | `torch.Tensor` value hash | `logical_types/torch_type.py:tensor_digest` | | pandas value hash | descriptor, `\0`, `b"arrow_ordered_v1:" + D` | SHA-256, `pandas_dataframe_v1` / `pandas_series_v1` | pandas value hash | `hashing/pandas_value_hash.py:pandas_frame_content_hash`, `hashing/pandas_value_hash.py:pandas_series_content_hash`, `hashing/labelled_hash.py:labelled_content_hash`, `hashing/semantic_hashing/builtin_handlers.py:PandasDataFrameHandler.digest`, `hashing/semantic_hashing/builtin_handlers.py:PandasSeriesHandler.digest` | @@ -365,7 +365,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | the `_content_hash` column | `core/streams/arrow_table_stream.py:ArrowTableStream._assemble_table..hashes`, `core/function_pod.py:FunctionPodStream.as_table..all_content_hashes`, `core/function_pod.py:FunctionPodStream.head..shown_content_hashes`, `core/function_pod.py:FunctionPodStream.head..`, `core/nodes/function_node.py:FunctionNodeBase.as_table..all_content_hashes`, `core/nodes/function_node.py:FunctionNodeBase._head_of_pairs..`, `side_effects.py:_table_of_rows` | | `__pf_var_function_signature_hash`, `__pf_var_function_content_hash` | `core/data_function.py:function_signature_hash`, `core/data_function.py:function_content_hash`, `core/data_function.py:PythonDataFunction.__init__` | | saved pipeline and job files | `pipeline/graph.py:Pipeline.save`, `pipeline/job.py:PipelineJob.save`, `pipeline/job.py:PipelineJob.as_pipeline`, `core/sources/base.py:RootSource._identity_config` | -| cached file hashes | `hashing/hash_cachers.py:SqliteHashCacher.put` | +| cached file hashes (SQLite and PostgreSQL read and write `b"sha256:" + digest` using validated fields) | `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put`, `hashing/postgres_hash_cacher.py:PostgresHashCacher.get`, `hashing/postgres_hash_cacher.py:PostgresHashCacher.put`, `hashing/file_hashers.py:parse_stored_file_hash`, `hashing/file_hashers.py:serialize_storable_file_hash` | | `InvocationContext.invocation_hash` (`