Skip to content

Match by Image-Data Hash for Import Dedup and the Immich Trash - #288

Merged
ptr727 merged 10 commits into
developfrom
feature/image-hash-dedup-trash
Nov 18, 2026
Merged

ptr727 merged 10 commits into
developfrom
feature/image-hash-dedup-trash

Conversation

@ptr727

@ptr727 ptr727 commented Nov 18, 2026 •

Copy link
Copy Markdown
Owner

Summary

Implements the proposal in issue 278. Files that differ only in metadata can now be matched by their image data hash, for both import dedup and the Immich trash match. Every new matching behaviour is opt-in. A run without the new options behaves exactly as before.

Closes on promotion: #278

New Options

  • --imagehash (import, process): also match files by image data hash.
    • import: a source whose image data hash is in --db is skipped as already imported, and the log names the row it matched. A source whose image data hash is in --trashdb is skipped as trashed in Immich. Requires --db or --trashdb.
    • process: a file whose cataloged image data hash is in --trashdb is deleted, like a SHA-1 match. Requires --db and --trashdb, since process checks the trash only with a database.
  • --processdb <path> (trash, optional, read-only, must exist): after the sync, trash looks up every trash row that has no image hash yet, by its SHA-1, in the process database. It records each image_hash it finds. That includes rows of assets the server has already purged. Without it, trash works as before.

One --imagehash switch covers both dedup and the trash match, because both make the same trade: equal image data with different metadata counts as one file. The name follows the existing lowercase single-word style (--rehash, --skipdb, --trashdb). --processdb follows --skipdb and --trashdb. It is not --db, because on trash that would read as the trash database.

Behaviour

  • The whole-file checks still run first, in their existing order. The image data hash is read only when they find no match.
  • Import reads the catalog metadata once for that check and reuses it for the rest of the file.
  • A null or empty image data hash never matches, so a format ExifTool cannot hash (GIF, for one) keeps whole-file matching.
  • The trash database gains an image_hash column (indexed). An older trash database is upgraded in place with ALTER TABLE when trash opens it. import and process open it read-only. On an old one --imagehash logs a warning and matches by SHA-1 only.
  • The trash insert is now an upsert. An existing row keeps its name and gains an image hash it lacked.
  • With --db, import claims each file's SHA-256, and its image hash under --imagehash, for the run. A file that meets another file's claim waits for that file's outcome. It skips when the owner imported, and claims again when the owner released the claim by not importing. Two matching files handled in parallel then import once, as a sequential run already did. SHA-256 is always claimed before the image hash, and no file waits while holding an image hash, so the waits cannot form a cycle. This also closes the same check-then-insert window on the existing SHA-256 dedup, which the local review raised. A visible effect on default runs: a --dryrun --db run now reports a byte-identical second copy as skipped rather than imported, matching what the real run does.
  • A trashed copy's image hash also matches a kept copy that differs only in metadata. After a duplicate cull in the server, process --imagehash deletes the kept copy's processed file. README and GUIDE warn about this. It follows from the issue's "treat as one file" trade-off, and it is one more reason the option is opt-in.
  • A process database too old to have image_hash, opened read-only by trash --processdb, logs a warning and records no image hashes.
  • Options.ImageHash is not a required member. So existing Options initializers elsewhere in the tests keep whole-file behaviour without edits.

Tests

  • Import dedup by image hash, with the option on and off (metadata-only copy of an imported file).
  • Import trash match by image hash, with the option on and off.
  • Process trash match by image hash, with the option on and off.
  • A GIF with no image hash never matches rows that have none, in either database.
  • Trash recording with and without --processdb, including the backfill of a row whose asset the server has purged.
  • In-run claims: a dry run with matching files imports once (by SHA-256, and by image hash). When a claiming file fails to import, the later match still imports. A waiter on a running owner claims when it releases and skips when it imports, and a cancelled waiter throws without claiming.
  • The trash upsert keeps a stored name and image hash and fills a missing one.
  • Trash database schema upgrade, read-write (adds the column, keeps the row, backfills) and read-only (matches by SHA-1 only).
  • Database lookups by image hash and by SHA-1, null and empty hashes, and a read-only old-schema database.
  • CLI parsing and validators for --imagehash and --processdb.

dotnet test: 433 total, 426 passed, 7 skipped (existing Docker and case-sensitivity skips), 0 failed.

Docs

README.md (option reference, help output, examples, import and trash flows, the workflow example line that pointed at issue 278), ARCHITECTURE.md, GUIDE.md, and OPERATIONS.md.

The change adds code comments, so it carries the comments label.

Local Review Findings Fixed After Opening

The local review's last pre-opening pass left two introduced findings. Both are fixed in d980849, and the hosted review raised the same two:

  • PhotoCleaner/ImportTask.cs claim set: a file that lost a claim was skipped at once, even when the winner then failed. Now it waits for the winner's outcome, and it claims again when the winner releases the claim.
  • PhotoCleaner/CommandLine.cs: --trashdb, --skipdb, --processdb, and --apikey-file share one CreateExistingFileOption factory.

A later pass's findings are fixed in 6f55483:

  • The parallel claim test is order-independent.
  • An unreachable claim branch is gone.
  • Two GUIDE and README statements are corrected.

cspell.json gains imagehash and processdb (0548e55).

The pass over 0548e55 raised three introduced findings, all fixed in a21b252:

  • import --imagehash now checks the ExifTool version once up front.
  • The claim comment and ARCHITECTURE now say that only the counts match a sequential run.
  • Deterministic tests now cover a waiter on a running owner (released, then imported) and a cancelled waiter.

The pass over a21b252 raised three more, all fixed in 39feb51:

  • A test now pins the trash upsert contract: the stored name and hash are kept, and a missing hash is filled.
  • The timing-dependent parallel row of the claim-release test is gone.
  • A stale GetFileMetaAsync comment is corrected.

The pass over 39feb51 raised one: the "INSERT OR IGNORE deduplicates" comment in TrashCommandTests, which the upsert made false. It is fixed in 8dd5268.

The pass over 8dd5268 raised one more. The GUIDE step for un-marking files in a seeded import database named only SHA-256 twins. Fixed in af72e54: it now covers image-hash twins under --imagehash.

🤖 Generated with Claude Code

ptr727 and others added 3 commits November 18, 2026 12:22
Add an opt-in --imagehash option to import and process, and an optional
--processdb option to trash, so a copy that differs only in metadata can
be matched by its image data hash. Default runs keep whole-file matching.

- import --imagehash skips a source whose image data hash is in --db and
  logs the matched row, and skips one whose hash is in --trashdb.
- process --imagehash deletes a file whose cataloged image data hash is
  in --trashdb.
- trash --processdb records each trashed asset's image data hash, looked
  up by SHA-1 in a read-only process database.
- The trash database gains an image_hash column, upgraded in place.
- A null or empty image hash never matches.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- trash --processdb backfills every row without an image hash, so rows
  of assets already purged from the server gain one too.
- import claims each hash for the run, so two matching files handled in
  parallel import once, by SHA-256 and by image hash under --imagehash.
- --processdb is a command-line field read by CreateOptions, and a test
  covers its wiring to Options.DbFile.
- Trash and process databases share one column-name helper.
- Drop the empty-string guards no writer needs.
- Docs warn that a trashed copy's image hash also matches a kept copy,
  and no longer suggest index for backfilling an import database.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A file that claimed a hash and then failed or proved invalid kept the
claim, so a later match in the same run was skipped although nothing was
imported. The claims are now released on any outcome but Imported.

Drop the unreachable read-only guard from FindPathByImageHashAsync, whose
only caller opens the import database read-write and already rejects an
empty hash.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ptr727 ptr727 added the comments Permits the comment lines the pull request adds or edits, which the prose gate otherwise refuses label Nov 18, 2026
Copilot AI lite review requested due to automatic review settings November 18, 2026 20:43
@ptr727

ptr727 commented Nov 18, 2026

Copy link
Copy Markdown
Owner Author

A recorded local strict-review pass covers head 86ae1a5f536d3e1523db0626c2fb47d57e0eeaef, the content this pull request carries at that commit against develop, and it recorded 2 findings.

@coderabbitai

coderabbitai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 56.68790% with 204 lines in your changes missing coverage. Please review.
✅ Project coverage is 41.73%. Comparing base (a3158ce) to head (af72e54).
⚠️ Report is 118 commits behind head on develop.

Files with missing lines Patch % Lines
PhotoCleaner/ImportTask.cs 0.00% 124 Missing ⚠️
PhotoCleaner/ProcessTask.cs 0.00% 31 Missing ⚠️
PhotoCleaner/TrashCommand.cs 80.59% 21 Missing and 5 partials ⚠️
PhotoCleaner/TrashDatabase.cs 88.31% 7 Missing and 2 partials ⚠️
PhotoCleaner/ImportCommand.cs 0.00% 8 Missing ⚠️
PhotoCleaner/ProcessCommand.cs 0.00% 5 Missing ⚠️
PhotoCleaner/CommandLine.cs 98.11% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #288      +/-   ##
===========================================
- Coverage    43.37%   41.73%   -1.65%     
===========================================
  Files           28       27       -1     
  Lines         3896     4445     +549     
  Branches       306      390      +84     
===========================================
+ Hits          1690     1855     +165     
- Misses        2154     2520     +366     
- Partials        52       70      +18     
Flag Coverage Δ
dotnet 41.73% <56.68%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

A file that met another file's claim was skipped at once, so a winner
that then failed or proved invalid left both files unimported. A file
now waits for the claim owner's outcome, skipping when the owner
imported and claiming again when the owner released it. SHA-256 is
always claimed before the image hash, and no file waits while holding an
image hash, so the waits cannot form a cycle.

The file-exists validators for --trashdb, --skipdb, --processdb, and
--apikey-file move onto one CreateExistingFileOption factory.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The change still has an unresolved concurrency bug that can cause valid files to be skipped when a claim owner fails, along with duplicated validation logic that may diverge across database options.

2 open issues
What changed in this PR

This pull request adds opt-in image-data hash matching for import deduplication and Immich trash handling, while preserving whole-file hash behavior by default. It also supports backfilling trash records from a read-only process database.

Changes:

  • Adds --imagehash and --processdb CLI options with validation and documentation.
  • Extends import, process, and trash database flows with image-hash lookup, schema upgrades, upserts, and backfill support.
  • Adds coverage for matching behavior, migrations, CLI parsing, and concurrent import claims.
File Description
README.md Documents the new options, workflows, database schema, and image-hash tradeoffs.
PhotoCleanerTests/​TrashDatabaseTests.cs Tests trash database schema upgrades, upserts, image-hash storage, and lookups.
PhotoCleanerTests/​TrashCommandTests.cs Tests process-database image-hash backfilling, including purged assets.
PhotoCleanerTests/​ProcessTaskTests.cs Tests process deletion by matching trashed image hashes.
PhotoCleanerTests/​ImportTaskTests.cs Tests image-hash matching, GIF behavior, dry-run claims, and claim release.
PhotoCleanerTests/​DatabaseTests.cs Tests image-hash lookups and old-schema read-only behavior.
PhotoCleanerTests/​CommandLineTests.cs Tests parsing and validation for the new command-line options.
PhotoCleaner/​TrashDatabase.cs Adds the image-hash column, index, migration, upsert, and lookup operations.
PhotoCleaner/​TrashCommand.cs Syncs trash hashes and backfills image hashes from Process.db.
PhotoCleaner/​ProcessTask.cs Deletes processed files matching trashed image hashes.
PhotoCleaner/​ProcessCommand.cs Warns when image-hash matching cannot use an old trash schema.
PhotoCleaner/​ImportTask.cs Implements image-hash matching and in-run deduplication claims.
PhotoCleaner/​ImportCommand.cs Warns when an old read-only trash database lacks image-hash support.
PhotoCleaner/​Database.cs Adds image-hash lookup and process-database compatibility handling.
PhotoCleaner/​CommandLine.cs Adds and validates --imagehash and --processdb.
OPERATIONS.md Documents read-only database handling and schema upgrades.
GUIDE.md Adds operational guidance for image-hash matching and duplicate-cull risks.
ARCHITECTURE.md Describes image-hash matching, database behavior, and import claim handling.

Review effort: Lite

Comment thread PhotoCleaner/ImportTask.cs Resolved
Comment thread PhotoCleaner/CommandLine.cs Resolved
ptr727 and others added 2 commits November 18, 2026 12:51
- The parallel case of the claim-release test asserts only the outcome
  both claim orders share.
- Drop a claim branch that no enumerated run can reach.
- GUIDE no longer says identical files in one parallel run may both
  import, since the claim set imports one.
- The restored-asset note no longer advises deleting sibling rows, which
  a later trash sync refills. It says to leave --imagehash off instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add imagehash and processdb beside trashdb and skipdb, so the spell
check accepts the new --imagehash and --processdb options.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ptr727

ptr727 commented Nov 18, 2026

Copy link
Copy Markdown
Owner Author

A recorded local strict-review pass covers head 0548e551935163acf3350bcd1dd8d8aab8f7b953, the content this pull request carries at that commit against develop, and it recorded 3 findings.

ptr727 and others added 2 commits November 18, 2026 13:00
- import --imagehash checks the ExifTool version once before the run,
  so a trash-only import with an old ExifTool stops with one message
  instead of failing every file.
- The claim comment and ARCHITECTURE say only the counts match a
  sequential run, since which matching file imports depends on timing.
- ClaimedByAsync and the extracted ReleaseClaims are internal, and new
  tests cover a waiter on a running owner that releases and one that
  imports, and a cancelled waiter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- A test asserts that a later upsert keeps a stored name and image hash
  and fills a missing hash.
- The claim-release import test runs on one thread only, since its
  parallel row passed in either claim order; ClaimedByAsync tests cover
  the wait deterministically.
- Correct the GetFileMetaAsync comment, which an image-hash import
  without a database also reaches.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ptr727

ptr727 commented Nov 18, 2026

Copy link
Copy Markdown
Owner Author

A recorded local strict-review pass covers head 39feb51d8d97763349554141cb55f54c6ad265bf, the content this pull request carries at that commit against develop, and it recorded 1 finding.

ptr727 and others added 2 commits November 18, 2026 13:17
The duplicate-hash test said INSERT OR IGNORE deduplicates, but the
trash insert is now an upsert on sha1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The GUIDE step for un-marking files in a seeded import database named
only SHA-256 twins. With --imagehash, a row sharing the image hash still
skips the file, so the step now says to run that import without the
option or delete those rows too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ptr727

ptr727 commented Nov 18, 2026

Copy link
Copy Markdown
Owner Author

A recorded local strict-review pass covers head af72e5435690979ff37d2356222c93653a79558f, the content this pull request carries at that commit against develop, and it recorded 0 findings.

@ptr727
ptr727 merged commit 3731ff9 into develop Nov 18, 2026
23 checks passed
@ptr727
ptr727 deleted the feature/image-hash-dedup-trash branch November 18, 2026 22:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comments Permits the comment lines the pull request adds or edits, which the prose gate otherwise refuses

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants