Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
ac0e4ce
fix(hashing): use a cached file hash only for the algorithm that made…
eywalker Nov 26, 2026
0254962
test(hashing): alternating algorithms evict, never hit wrongly (ITL-1…
eywalker Nov 26, 2026
a623f5a
fix(hashing): refuse mislabelled cache puts and read stored hashes st…
eywalker Nov 26, 2026
25c5a4e
fix(hashing): treat every invalid cache label as ValueError on put, a…
eywalker Nov 26, 2026
9568b29
fix(hashing): turn any hashlib refusal of a cache label into ValueErr…
eywalker Nov 26, 2026
82f3c49
fix(hashing): refuse an uncacheable hasher label when CachedFileHashe…
eywalker Nov 26, 2026
d2469cf
fix(hashing): key file hash cache entries by algorithm
eywalker Nov 27, 2026
abf55e0
fix(hashing): validate custom cache hits and retry SQLite startup
eywalker Nov 27, 2026
0a12a35
fix(hashing): reject non-hash custom cache hits
eywalker Nov 27, 2026
b2c9dba
test(hashing): use the supported path type for the cache fixture
eywalker Nov 27, 2026
df79438
fix(cli): fail warm-cache when file processing reports errors
eywalker Nov 27, 2026
77eccbe
fix(hashing): repair malformed file hash cache rows
eywalker Nov 27, 2026
a065344
fix(hashing): preserve valid cache rows during repair
eywalker Nov 27, 2026
9c590e4
fix(hashing): canonicalize persistent file hash writes
eywalker Nov 27, 2026
7add0c2
fix(hashing): preserve cache rows with another algorithm label
eywalker Nov 27, 2026
2da1340
fix(hashing): compare PostgreSQL cache labels as bytes
eywalker Nov 28, 2026
2067af7
fix(hashing): clarify forced warming and guard ICU test setup
eywalker Nov 28, 2026
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
114 changes: 0 additions & 114 deletions .basedpyright/baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -35440,120 +35440,6 @@
}
}
],
"./src/orcapod/hashing/migrate_hash_cache.py": [
{
"code": "reportAny",
"range": {
"startColumn": 8,
"endColumn": 20,
"lineCount": 1
}
},
{
"code": "reportImplicitStringConcatenation",
"range": {
"startColumn": 12,
"endColumn": 59,
"lineCount": 2
}
},
{
"code": "reportImplicitStringConcatenation",
"range": {
"startColumn": 16,
"endColumn": 57,
"lineCount": 2
}
},
{
"code": "reportAny",
"range": {
"startColumn": 8,
"endColumn": 15,
"lineCount": 1
}
},
{
"code": "reportAny",
"range": {
"startColumn": 30,
"endColumn": 33,
"lineCount": 1
}
},
{
"code": "reportUnusedCallResult",
"range": {
"startColumn": 12,
"endColumn": 51,
"lineCount": 1
}
},
{
"code": "reportImplicitStringConcatenation",
"range": {
"startColumn": 16,
"endColumn": 47,
"lineCount": 2
}
},
{
"code": "reportUnusedCallResult",
"range": {
"startColumn": 8,
"endColumn": 9,
"lineCount": 4
}
},
{
"code": "reportImplicitStringConcatenation",
"range": {
"startColumn": 12,
"endColumn": 61,
"lineCount": 2
}
},
{
"code": "reportUnusedCallResult",
"range": {
"startColumn": 8,
"endColumn": 47,
"lineCount": 1
}
},
{
"code": "reportImplicitStringConcatenation",
"range": {
"startColumn": 12,
"endColumn": 62,
"lineCount": 2
}
},
{
"code": "reportUnusedCallResult",
"range": {
"startColumn": 4,
"endColumn": 5,
"lineCount": 5
}
},
{
"code": "reportAny",
"range": {
"startColumn": 30,
"endColumn": 42,
"lineCount": 1
}
},
{
"code": "reportAny",
"range": {
"startColumn": 30,
"endColumn": 42,
"lineCount": 1
}
}
],
"./src/orcapod/hashing/postgres_hash_cacher.py": [
{
"code": "reportImplicitStringConcatenation",
Expand Down
24 changes: 24 additions & 0 deletions changelog.d/ITL-1488.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
### Fixed

- File hash caches now key entries by path, modification time, size, and algorithm.
Hashes for different algorithms coexist. A hasher declares its hash label through
`FileContentHasherProtocol.hash_algorithm`, and the cache key carries it in the
provisional `FileHashKey.algorithm` field.
- A cache put raises `ValueError` for a mismatched label, an invalid digest length,
or a different well-formed hash already stored under the same key. Putting an
identical hash preserves its timestamp. SQLite and PostgreSQL treat malformed
stored values as misses. The next valid put for the same key replaces the
malformed value, refreshes its timestamp, and logs a warning naming the file
and algorithm.

### Changed

- Scripts can now detect per-file errors, including `--force` conflicts, through the `orcapod warm-cache` exit status `1`.

### Breaking changes and migration

- SQLite and PostgreSQL use `file_hash_cache_v2` (schema version 2) and leave the
previous `file_hash_cache` table untouched. The old SQLite migration helper
was removed. ITL-1535 tracks migration of both older SQLite layouts (with and
without `cached_at`). Until migration is available, let the next pipeline run
or `orcapod warm-cache` hash the files once more to fill the new table.
74 changes: 59 additions & 15 deletions docs/concepts/file-hash-caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,52 @@ default, configurable via the `algorithm` argument). It does this every time,
with no memory of previous results.

`HashCacher` is a protocol for any object that maps a `FileHashKey` to a
`ContentHash`. The key is a three-field struct:
`ContentHash`. The key is a four-field struct:

```
FileHashKey(path, mtime_ns, size)
FileHashKey(path, mtime_ns, size, algorithm)
```

The `mtime_ns` and `size` fields encode the file's identity at a specific
point in time. If the file is modified — its modification time or byte count
changes — the key is different, so the old entry is never returned. You do
not need to explicitly invalidate entries; the key change handles it
automatically.
An ordinary lookup trusts the file's resolved path, nanosecond modification
time, and byte size. A change to any of these fields gives the file a
different key in the default lookup mode. If a file is rewritten to the same
size at the same path and its original modification time is restored, the
lookup returns the cached hash without reading the file. This hit bypasses
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.

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
an identical hash leaves the existing entry and its timestamp unchanged. Reads
accept values in the exact format `<label>:<digest>`, with the key's label and
that algorithm's digest length. The persistent caches treat malformed values
as misses. The next valid write for the same key replaces the malformed value,
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.
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
surface as `RuntimeError: Failed to process column 'recording'`, with a
`ValueError` cause beginning `Different hash already cached for FileHashKey`
and naming the file and algorithm. To replace a stale valid hash, clear the
[current cache](#cache-storage) and rerun the pipeline or warmer to rebuild the
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` 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 Expand Up @@ -127,7 +162,7 @@ enable_file_hash_caching(

## Ignoring mtime in cache lookups

By default, a cache hit requires **path, mtime_ns, and size** to all match the stored
By default, a cache hit requires **path, mtime_ns, size, and algorithm** to all match the stored
entry. In several common deployment scenarios, mtime is unreliable — it changes even
when file content has not — causing spurious cache misses and unnecessary re-hashing:

Expand All @@ -148,15 +183,15 @@ when file content has not — causing spurious cache misses and unnecessary re-h
timestamps that differ from the values recorded in the cache.

Set `match_mtime=False` to drop mtime from the lookup criterion. A cache hit then
requires only **path and size** to match:
requires **path, size, and algorithm** to match:

```python
from orcapod.contexts import enable_file_hash_caching

enable_file_hash_caching(match_mtime=False)
```

When multiple cache entries share the same path and size (recorded at different
When multiple cache entries share the same path, size, and algorithm (recorded at different
mtimes), Orcapod returns the hash from the entry with the most recent `mtime_ns`.

**The write path is unchanged.** mtime is always recorded when a new entry is
Expand Down Expand Up @@ -204,16 +239,24 @@ You can override this path in two ways:
- Set the `ORCAPOD_HASH_CACHE_DB` environment variable to the desired path.
- Pass the `db_path` argument to `enable_file_hash_caching()`.

SQLite and PostgreSQL use the new `file_hash_cache_v2` table. The old
`file_hash_cache` table remains untouched and the cacher reads only the new
table. SQLite uses `PRAGMA user_version` to record the layout of the new table.
PostgreSQL records version 2 in `file_hash_cache_v2_meta`. ITL-1535 tracks
migration of old caches, including both SQLite layouts (with and without
`cached_at`). Let your next pipeline run or `orcapod warm-cache` hash the files
once more to fill the new table.

To inspect cached entries using the SQLite command-line tool:

```bash
sqlite3 ~/.orcapod/file_hash_cache.db "SELECT path, size, cached_at FROM file_hash_cache LIMIT 10;"
sqlite3 ~/.orcapod/file_hash_cache.db "SELECT path, size, algorithm, cached_at FROM file_hash_cache_v2 LIMIT 10;"
```

To clear all cached entries:

```bash
sqlite3 ~/.orcapod/file_hash_cache.db "DELETE FROM file_hash_cache;"
sqlite3 ~/.orcapod/file_hash_cache.db "DELETE FROM file_hash_cache_v2;"
```

## When caching helps -- and when it doesn't
Expand Down Expand Up @@ -248,7 +291,7 @@ Orcapod ships two hash cache backends. Pick based on your deployment:
|---|---|---|
| Setup | Zero — file on disk | Requires a running Postgres server |
| Scope | Per-machine | Shared across machines and pipeline runs |
| Concurrency | Single-writer | Multi-writer safe (`ON CONFLICT DO NOTHING`) |
| Concurrency | One writer at a time | Concurrent writers |
| Best for | Local development, single-machine pipelines | Distributed pipelines, shared caches |

### Using the SQLite backend (default)
Expand Down Expand Up @@ -298,13 +341,14 @@ hasher = CachedFileHasher(file_hasher=FileHasher(), cacher=cacher)
(`CREATE TABLE IF NOT EXISTS`):

```sql
CREATE TABLE IF NOT EXISTS file_hash_cache (
CREATE TABLE IF NOT EXISTS file_hash_cache_v2 (
path TEXT NOT NULL,
mtime_ns BIGINT NOT NULL,
size BIGINT NOT NULL,
algorithm TEXT NOT NULL,
hash BYTEA NOT NULL,
cached_at BIGINT NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())::BIGINT,
PRIMARY KEY (path, mtime_ns, size)
PRIMARY KEY (path, mtime_ns, size, algorithm)
)
```

Expand Down
3 changes: 2 additions & 1 deletion docs/concepts/file-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,8 @@ for _, data in total_lines.pod(everything):
## Large files

Hashing a file means reading it. For large files Orcapod can cache the hash, keyed by the
file's path, size and modification time, so that an unchanged file is not read again:
file's path, size and modification time and the hash algorithm, so that an unchanged file is
not read again (a hash cached by another algorithm is never used):

```python
op.enable_file_hash_caching()
Expand Down
41 changes: 41 additions & 0 deletions docs/dev/plans/2026-11-26-itl-1488-file-hash-cache-algorithm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# ITL-1488 file hash cache algorithm

`CachedFileHasher` keyed entries by path, modification time, and byte size.
After `orcapod warm-cache --force --algorithm md5`, the default SHA-256 file
handler could return the MD5 hash with caching enabled.

## Developer decisions on November 27, 2026

- Key all cachers by `(path, mtime_ns, size, algorithm)`. With
`match_mtime=False`, reads select the latest matching entry within the
requested algorithm. Writes always use the full key.
- A duplicate put of the same hash is a no-op. A different well-formed hash
under the same key raises `ValueError`. The persistent cachers compare and
repair malformed values in the same transaction as the insert attempt. A
repair refreshes `cached_at` and warns with the file and algorithm. To
replace a stale valid hash, clear the cache and rebuild it. An explicit
replacement operation is tracked separately (ITL-1547).
- `FileHashKey.algorithm` is provisional and carries the hash label supplied
by `FileContentHasherProtocol.hash_algorithm`. Cache warming uses that field
for actual writes and dry-run counts.
- Store new rows in `file_hash_cache_v2` on both persistent backends. Keep the
old table beside it and leave its data and schema untouched. SQLite uses
`PRAGMA user_version` for the new table's layout. PostgreSQL records version 2
in `file_hash_cache_v2_meta`. Remove the old SQLite migration helper. ITL-1535
tracks migration into v2 from both old SQLite layouts (with and without
`cached_at`).
- Keep strict write validation and treat malformed stored values as misses.
Refusals from `hashlib.new` surface as `ValueError` for a put.

## Regression coverage

`tests/test_hashing/test_file_hash_cache_algorithm.py` covers both algorithm
orders, the default file handler, warming and dry-run statistics, lookup with
mtime disabled, strict validation, and concurrent SQLite writes.
`tests/test_hashing/test_hash_cachers.py` verifies legacy SQLite schemas and
the unchanged timestamp of an identical put.
`tests/test_hashing/test_postgres_hash_cacher.py` covers both algorithm orders,
legacy-table isolation, and identical and conflicting concurrent writers.
Both persistent cacher suites cover malformed-row repair and concurrent puts
against a malformed row. The PostgreSQL fixture creates a test-owned schema
and checks that cache operations and cleanup leave public cache tables intact.
6 changes: 5 additions & 1 deletion src/orcapod/cli/warm_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import typer
from upath import UPath

from orcapod.hashing.hash_utils import SHA256_ALGORITHM

_DEFAULT_MIN_SIZE_MB: float = 500.0


Expand All @@ -31,7 +33,7 @@ def warm_cache(
),
),
algorithm: str = typer.Option(
"sha256",
SHA256_ALGORITHM,
"--algorithm",
help="Hash algorithm (sha256, xxh64, md5, …). Default: sha256.",
show_default=True,
Expand Down Expand Up @@ -123,3 +125,5 @@ def warm_cache(
)
if stats.hashed > 0:
typer.echo(f"Average hashing speed: {speed_gb:.2f} GB/s")
if stats.errors:
raise typer.Exit(code=1)
6 changes: 3 additions & 3 deletions src/orcapod/contexts/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,9 +321,9 @@ def enable_file_hash_caching(
are not inserted into the cache. ``None`` and ``0`` disable the
threshold. Defaults to ``None``.
match_mtime: When ``True`` (default), cache lookups require an exact
match on ``path``, ``mtime_ns``, and ``size``. When ``False``,
only ``path`` and ``size`` are used for matching — an mtime
change alone will not cause a cache miss. Useful for environments
match on ``path``, ``mtime_ns``, ``size``, and ``algorithm``. When
``False``, lookups match ``path``, ``size``, and ``algorithm`` and
select the newest matching entry. Useful for environments
where file timestamps
are unreliable (e.g. network filesystems or build tools that
preserve content but reset mtimes). Note that with
Expand Down
7 changes: 2 additions & 5 deletions src/orcapod/contexts/data/v1.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,14 @@
"previous": "std:v0.1:default",
"file_hasher": {
"_class": "orcapod.hashing.file_hashers.FileHasher",
"_config": {
"algorithm": "sha256"
}
"_config": {}
},
"directory_hasher": {
"_class": "orcapod.hashing.directory_hashers.BasicDirectoryHasher",
"_config": {
"file_hasher": {
"_ref": "file_hasher"
},
"algorithm": "sha256"
}
}
},
"type_converter": {
Expand Down
Loading
Loading