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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions changelog.d/ITL-1155.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
### 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 remove the `algorithm` argument from `populate_hash_cache` and
`hash_file` calls.
- Custom `DirectoryHasherProtocol` implementations must expose
`algorithm = "sha256"` and return the standard `directory_v1` Merkle digest.
Register custom backends through `DirectoryHandler` and `FileHandler` to use
them for logical values.

### 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. 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
or invoking a custom file or directory hasher. Verify custom hasher results
against SHA-256 of the file's bytes or the standard `directory_v1` Merkle tree.
Handlers for `File` or `Directory` subclasses can still describe their semantic
identity with `Encoded`.
26 changes: 14 additions & 12 deletions docs/concepts/file-hash-caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@ 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. The standalone `hash_file(path)` function also computes SHA-256 and
takes only the path and an optional buffer size. `FileHasher(algorithm=...)`
accepts only `"sha256"` and raises `ValueError` for other names. 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:
Expand All @@ -31,9 +35,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
Expand All @@ -45,8 +50,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
Expand All @@ -58,10 +62,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
Expand Down
22 changes: 22 additions & 0 deletions docs/dev/design_issues/ITL-1155-FH1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
## 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 built-in and custom file hashers and cache writes. Use fixed SHA-256 implementations and read-only algorithm properties. Verify
custom hasher declarations and digest widths, then compare custom file and
directory results to the library's SHA-256 and `directory_v1` computations.
Route registered File and Directory content handlers through this verification.
Subclass handlers can still describe their semantic identity with `Encoded`.
Validate directory ignore patterns before sharing them across both traversals.
Check custom hasher and cacher declarations after a cache lookup. 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.
12 changes: 5 additions & 7 deletions docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
8 changes: 4 additions & 4 deletions docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -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 | 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` |
| 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 hasher results are verified against SHA-256 of the file bytes. | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/semantic_hashing/builtin_handlers.py:FileHandler.handle`, `hashing/file_hashers.py:verified_file_hash`, `hashing/file_hashers.py:canonical_file_hash`, `hashing/file_hashers.py:_validated_file_digest`, `hashing/hash_cachers.py:InMemoryHashCacher.put`, `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 verifies custom directory hashes against the library Merkle procedure. | `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:verified_directory_hash`, `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` |
Expand Down Expand Up @@ -366,7 +366,7 @@ test session with `-p tests.test_hashing.hash_site_trace`.
| the `_content_hash` column | `core/streams/arrow_table_stream.py:ArrowTableStream._assemble_table.<locals>.hashes`, `core/function_pod.py:FunctionPodStream.as_table.<locals>.all_content_hashes`, `core/function_pod.py:FunctionPodStream.head.<locals>.shown_content_hashes`, `core/function_pod.py:FunctionPodStream.head.<locals>.<lambda>`, `core/nodes/function_node.py:FunctionNodeBase.as_table.<locals>.all_content_hashes`, `core/nodes/function_node.py:FunctionNodeBase._head_of_pairs.<locals>.<lambda>`, `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 (in-memory writes compare validated hashes, SQLite and PostgreSQL read and write `b"sha256:" + digest`) | `hashing/hash_cachers.py:InMemoryHashCacher.put`, `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` (`<label>:<hex>::<label>:<hex>`; its redesign is a side-effect follow-up) | `invocation.py:_serialize_component` |

### In a name (bare hex)
Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
9 changes: 0 additions & 9 deletions src/orcapod/cli/warm_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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",
Expand Down Expand Up @@ -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,
Expand Down
65 changes: 64 additions & 1 deletion src/orcapod/contexts/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,36 @@ def _read_json_file(path: Path) -> Any:
raise ContextValidationError(f"{path}: {error}") from error


def _validate_path_hasher_spec(spec: Any, kind: str, ref_lut: dict[str, Any]) -> Any:
"""Require SHA-256 for algorithm settings in file and directory components."""
from orcapod.hashing.directory_hashers import require_directory_hash_algorithm
from orcapod.hashing.hash_utils import (
SHA256_ALGORITHM,
require_file_hash_algorithm,
)

if not isinstance(spec, dict) or "_class" not in spec:
return spec
config = spec.get("_config")
if not isinstance(config, dict):
return spec

config = dict(config)
if "algorithm" in config:
algorithm = parse_objectspec(config["algorithm"], ref_lut=ref_lut)
if kind == "directory_hasher":
require_directory_hash_algorithm(algorithm)
else:
require_file_hash_algorithm(algorithm)
config["algorithm"] = SHA256_ALGORITHM
for dependency in ("file_hasher", "directory_hasher", "cacher"):
if dependency in config:
config[dependency] = _validate_path_hasher_spec(
config[dependency], dependency, ref_lut
)
return {**spec, "_config": config}


class JSONDataContextRegistry:
"""
Registry that loads data contexts from JSON files with validation.
Expand Down Expand Up @@ -414,6 +444,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.directory_hashers import require_directory_hash_algorithm
from orcapod.hashing.hash_utils import require_file_hash_algorithm
from orcapod.logical_types.directory_type import Directory
from orcapod.logical_types.file_type import File

try:
context_key = spec["context_key"]
version = spec["version"]
Expand Down Expand Up @@ -460,7 +495,18 @@ 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)
if key in ("file_hasher", "directory_hasher"):
value = _validate_path_hasher_spec(value, key, ref_lut)
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", 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`` ...).
Expand All @@ -469,6 +515,23 @@ def _create_context_from_spec(self, spec: dict[str, Any]) -> DataContext:
for pair_spec in registration["value_handlers"]:
# As for the handlers of the context file: a pair whose type or
# handler is optional and not installed is skipped.
if isinstance(pair_spec, list) and len(pair_spec) == 2:
type_spec, handler_spec = pair_spec
if isinstance(type_spec, dict) and "_type" in type_spec:
value_type = parse_objectspec(type_spec, ref_lut=ref_lut)
if isinstance(value_type, type) and issubclass(
value_type, File
):
handler_spec = _validate_path_hasher_spec(
handler_spec, "file_hasher", ref_lut
)
elif isinstance(value_type, type) and issubclass(
value_type, Directory
):
handler_spec = _validate_path_hasher_spec(
handler_spec, "directory_hasher", ref_lut
)
pair_spec = [type_spec, handler_spec]
pair = parse_objectspec(pair_spec, ref_lut=ref_lut)
if pair and len(pair) == 2 and all(x is not None for x in pair):
handler_registry.register(pair[0], pair[1])
Expand Down
Loading
Loading