Skip to content

Duplicates: say why files were left; ask before deleting Recycle Bin refusals; count hard links once; drop ImageSharp - #2

Merged
0langa merged 4 commits into
mainfrom
r3/duplicates-safety
Oct 14, 2026
Merged

0langa merged 4 commits into
mainfrom
r3/duplicates-safety

Conversation

@0langa

@0langa 0langa commented Oct 14, 2026

Copy link
Copy Markdown
Owner

Summary

Round 3 of the 2026-10-14 audit. It covers the StorageMaster items left open after #1:

  1. Duplicates page: why a selected file was not deleted. Each file left in place is now listed with its reason, in all three UI languages.
  2. Recycle Bin refusals get a second confirmation. "Delete these N item(s) permanently?" lists the items and defaults to No.
  3. Hard links count once in folder, category and scan totals.
  4. ImageSharp is replaced with the Windows Imaging Component, and the package is removed. That clears all five advisories (dotnet build now reports 0 warnings).
  5. Online-only files stay excluded from duplicate detection, as decided. No change was needed.

Changes

Why a duplicate was not deleted (feat(delete))

  • DuplicateDeletionService.DeleteSelectedWithResultAsync returns Skipped: one DuplicateDeletionSkip per selected file it left in place. The reasons are:
    • changed since the analysis
    • could not be re-read to verify
    • no longer matches the kept file
    • refused by Windows (with Windows' own message as detail)
    • Recycle Bin unavailable
    • no stable identity
  • If a group's keeper cannot be verified, every selected file in that group is listed as "kept file could not be verified".
  • The no-identity case used to show up as a "bookkeeping warning". It is now a skip with a reason.
  • The Duplicates page shows a warning banner under the status row. It lists each path with its localized reason, plus technical detail when there is any. The banner clears on the next deletion or a session change.
  • New Safety_Duplicates_NotDeleted_* strings in en-US, de-DE and es-ES follow the glossary ("beizubehaltende Datei", "archivo que se conserva", Papierkorb/Papelera de reciclaje). A test checks that every reason has a string in every language.

Second confirmation for Recycle Bin refusals (feat(delete))

  • DeletionOutcome.RecycleBinRefused is set when FileDeleter refuses an item that Windows could only delete permanently, for both single items and batches. A locked file is not a refusal.
  • The interactive flows now ask Safety_RecycleRefused_* ("Delete these N item(s) permanently?"). The dialog lists the items and its default button is No, keep them:
    • Duplicates: a yes re-runs only the refused members, as a permanent deletion, through the full service. The keeper is re-locked and re-hashed, and every member is snapshot-checked again.
    • Cleanup: after the Recycle Bin report closes, the question is asked. A yes runs the engine on the suggestions narrowed to the refused targets (CleanupEngine.BuildPermanentRetryForRecycleBinRefusals). Suggestions the engine may not delete permanently (high risk, or no permanent support) contribute nothing. The next report shows that run.
    • Smart Cleaner: the groups are narrowed to the refused paths (SmartCleanerService.NarrowToRecycleBinRefusals). Paths are revalidated against their analysis-time snapshots, and the summaries are reported separately. A cancelled run never asks.
    • Results page, single file: same question; a yes calls the existing permanent path.
  • Scheduled cleanup has no one to ask, so it keeps the refusal.
  • The dialog is in ScenarioCatalogue for the capture harness. SafetyDialogCoverageTests now also reads ConfirmItemsAsync call sites.
  • Source guards (PageViewModelThreadingGuardTests) pin two things:
    • each permanent retry sits behind if (deletePermanently), after the listed question;
    • the dialog's default is Close.

Hard links count once (fix(scan))

  • A new HardLinkTracker keys files by volume + file index (about 8 bytes per file) and is thread-safe for the parallel managed scanner.
  • In both scanners, the first name reached carries the size. Every further name is still listed with its real SizeBytes, but is marked IsAdditionalHardLink and adds nothing to folder, progress or session totals.
  • Schema v16 adds FileEntries.IsAdditionalHardLink (default 0), so the SQL category breakdown counts shared data once. Older rows read exactly as before.
  • Docs record v16 in README, ARCHITECTURE, CODEMAP and DOCUMENTATION; the schema documentation test enforces this.
  • Two test fixtures changed:
    • The managed-scanner fixture gave every file the same identity, which now means "one file with many links". It returns one identity per path.
    • The v13 migration fixture gains the FileEntries table every real database has.

ImageSharp replaced (refactor(dedupe))

  • I judged the replacement small and contained: three call sites and one DI registration. IImageHashDecoder lives in Core; WicImageHashDecoder (Platform.Windows) implements it on Windows.Graphics.Imaging. The decoder:
    • applies EXIF orientation;
    • scales to 32×32 with Fant resampling inside the decode, so JPEG decodes at reduced size;
    • reports the displayed dimensions;
    • names the HRESULT when it fails.
  • Video frames: FFmpeg now writes 1024 raw grey bytes per frame (scale=32:32,format=gray -f rawvideo), so no image decoder is needed. A short frame is rejected.
  • The duplicate preview reads dimensions from the same decoder.
  • Image and video algorithm versions are bumped to 3, so cached fingerprints are recomputed on the next analysis. Existing groups stay deletable, because deletion recomputes both live signatures.
  • Formats with an installed Windows codec (HEIC with the HEIF extension, WebP) now decode. ImageSharp could never decode HEIC.

Verification

  • Every ci.yml step ran locally on the final tree:
    • cargo fmt --check, clippy -D warnings, cargo test and cargo build --release (Rust is unchanged)
    • dotnet format --verify-no-changes
    • Release build: 0 warnings, 0 errors (it had 5 ImageSharp advisory warnings before)
    • dotnet test with STORAGEMASTER_REQUIRE_TURBO_SCANNER=true and the freshly built binary: 600 passed, 1 intentional skip (567 + 1 skip before)
  • New tests:
    • Skip reasons: one test covers six members that each hit a different reason. Others cover a member that cannot be re-read, the keeper-not-verified expansion, the retry selection (never selects anything the user was not asked about), and an end-to-end refusal → permanent retry that checks only the refused file gets a permanent request, with its snapshot.
    • Cleanup and Smart Cleaner: refusals are reported apart from other failures. The retry narrowing respects the engine's permanent-delete policy and ignores dry runs and foreign paths.
    • RecycleBinGuardTests now also assert the new flag. On this machine the \\localhost\C$ cases run in full, not their early return.
    • Hard links: a managed scan over real hard links created in a temp folder; a turbo scan with injected records that share an identity; the category breakdown against a real SQLite file.
    • WIC: fixtures are drawn and encoded through WIC in a temp folder. PNG and BMP hash identically, JPEG within 4 bits, and the negative image far apart. An orientation-6 JPEG hashes like the upright picture and reports upright dimensions. An undecodable file becomes a per-file error, and Rec. 709 luma is checked. A guard confirms Core references no SixLabors assembly.
  • Tests that delete only touch temp folders they create (sm_dupdelete_*, sm_recycle_guard_*, sm_hardlink_*, sm_phash_*), or go through mocked deleters.
  • Not verified on screen: the new banner and dialog. Both use existing controls and patterns (an InfoBar, and a ContentDialog built like the Cleanup report). The XAML compiles in the Release build. I did not run the capture harness.

Left alone, and why

  • Size of hard-linked files on the per-file lists (Large files and so on) is still each file's real size. That is a file property, and deleting one name frees nothing. Only totals changed.
  • Older scans keep counting every link. Comparing a new scan with an older one therefore shows hard-linked folders (WinSxS) shrinking once.
  • The ImageSharp license question is moot: the package is gone.

🤖 Generated with Claude Code

0langa and others added 4 commits October 14, 2026 22:45
ImageSharp 3.1.12 carries five security advisories that are fixed only in
4.x, which refuses to build without a commercial license key. Its use here
was small: decode an image to a 32x32 grey surface for the perceptual hash,
read a PNG frame for the video hash, and read dimensions for the preview.

- Images: a new IImageHashDecoder, implemented in Platform.Windows on the
  Windows Imaging Component (Windows.Graphics.Imaging). It applies EXIF
  orientation, scales to 32x32 with Fant resampling inside the decode, and
  reports the displayed dimensions. Decode failures name the HRESULT
  instead of surfacing as a blank error.
- Video: FFmpeg now writes each sampled frame as 1024 raw grey bytes, so no
  image decoder is involved; a short frame is rejected.
- Preview: dimensions come from the same decoder's header read.
- The package reference is gone, and with it the NU1902/NU1903 warnings.

Resampling differs slightly, so the image and video algorithm versions move
to 3 and cached fingerprints are recomputed on the next analysis.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A file with several hard links is one file on disk, but each name added its
size to folder, category and session totals. Windows links most of WinSxS
this way, so a system drive scanned noticeably fuller than it is.

Both scanners now keep a HardLinkTracker (volume + file index, about 8 bytes
per file). The first name a scan reaches carries the size; every further
name is still listed with its real size, is marked IsAdditionalHardLink and
adds nothing to folder, session or progress totals. Files without a stable
identity are always counted, as before.

Schema v16 persists that flag so the SQL category breakdown counts the
shared data once too. Older rows default to 0 and read as they did.

The managed-scanner test fixture gave every file the same identity, which
now means "all hard links of one file"; it returns one identity per path.
The v13 migration fixture gains the FileEntries table every real database
has. Docs: schema v16 in README, ARCHITECTURE, CODEMAP and DOCUMENTATION;
CODEMAP also drops ImageSharp from the package lists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ecycle Bin refusals

Duplicates page: DuplicateDeletionService now returns a reason for every
selected file it left in place (changed since the analysis, could not be
re-read, no longer matches the kept file, refused by Windows, Recycle Bin
unavailable, no stable identity), and a group whose keeper cannot be
verified lists its selected files as such. The page shows them in a
warning banner with the reason under each path, in English, German and
Spanish. Before, the status line only showed a lower count.

Recycle Bin refusals: DeletionOutcome.RecycleBinRefused marks items Windows
could only have deleted permanently. Duplicates, Cleanup, Smart Cleaner and
the Results page follow such a refusal with a second confirmation, "Delete
these N item(s) permanently?", that lists the items and defaults to No. A
yes re-runs only those items as a permanent deletion through the normal
checks (keeper re-verification, snapshots, cleanup policy); nothing else is
selected. Scheduled cleanup keeps the refusal. The new dialog is in the
capture catalogue, and the coverage test now also reads ConfirmItemsAsync.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
File systems that cannot give a file a unique 64-bit id report 0 or all
ones instead: ReFS (Dev Drive) for files whose 128-bit id does not fit,
and some network and user-mode file systems for every file. Unrelated
files share those values, so the hard-link tracker folded them into one
file and left all but the first out of the folder, category and session
totals. Those ids are now always counted, like a missing identity.

Also adds review tests:
- v15 -> v16 migration of a real v15 database keeps every row and every
  category total, and reopening does not migrate twice.
- damaged images (empty, header-only, truncated, not an image) never
  throw out of the image hash, and the decoder releases the file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@0langa

0langa commented Oct 14, 2026

Copy link
Copy Markdown
Owner Author

Review: approve, with one fix pushed (74f16d1)

I checked out the PR head in a separate worktree, read the full diff and the code around it, and ran every ci.yml step locally:

  • cargo fmt --check, clippy -D warnings, cargo test, cargo build --release
  • dotnet format --verify-no-changes
  • Release build: 0 warnings
  • dotnet test with the Turbo Scanner required: 606 passed, 1 intentional skip

CI is green on the fix commit.

Fix: a placeholder file id was treated as a hard link (fix(scan))

HardLinkTracker trusted every (volume, file index) pair. Some file systems cannot give a file a unique 64-bit id and report a placeholder instead:

  • ReFS, including Dev Drives, reports 0xFFFFFFFFFFFFFFFF (FSCC's "no unique id") for files whose 128-bit id does not fit in 64 bits.
  • Some network and user-mode (FUSE-style) file systems report 0 for every file.

Unrelated files share those values. The tracker would therefore have marked every file after the first as an additional hard link, and the folder, category and session totals would have dropped to almost nothing on such a volume. Ids of 0 and all ones are now always counted, the same way a missing identity already was.

Tests, which fail without the fix:

  • a tracker theory for both placeholder values;
  • a Turbo scan with injected records that share placeholder ids, where all four files must count.

Review tests added (no behaviour change)

  • SchemaV16MigrationTests. Builds a real v15 database by applying V1–V15 in order, then writes a scan with the v15 column set, including two names that share one identity. It then checks that:

    • the upgrade to v16 keeps all rows;
    • the new column is NOT NULL DEFAULT 0 and every old row is 0;
    • the category breakdown is unchanged (old scans keep counting every name);
    • new rows insert normally;
    • reopening the database does not migrate a second time.

    The migration itself is a single ALTER TABLE … ADD COLUMN … DEFAULT 0 inside the existing atomic migration transaction. SQLite does not rewrite the table for that.

  • DamagedFiles_NeverThrow_AndAreClosedAfterwards. Covers empty, one-byte, header-only, text and noise files, plus a truncated JPEG. Each must come back as a per-file result, never an exception, and the file must be openable with FileShare.None afterwards, so the decoder leaks no handle.

What I checked

  • WIC replacing ImageSharp.
    • Leak and stability check, run locally and not committed: 1,200 decodes of a 12 MP JPEG and a 6 MP PNG. Private bytes stayed flat at about 70 MB, so nothing accumulates even though WinRT decoders are only released by the GC.
    • Bad input: malformed and truncated files, and a PNG that claims to be 60000×60000, never threw. Handles were released every time.
    • The preview service only reads dimensions, inside a catch-all. The thumbnails themselves are still the XAML image from PreviewPath and are unchanged.
    • No SixLabors reference remains in code, lockfiles, the installer or docs, and trimming is off.
  • Recycle Bin second confirmation.
    • ConfirmItemsAsync always uses DefaultButton = Close ("No, keep them"), so Enter and Esc both keep the items.
    • Each of the four flows deletes only after a true answer, and only the refused items:
      • Duplicates re-runs the full service with everything else deselected. The keeper is re-locked and re-hashed, and every member is snapshot-checked.
      • Cleanup narrows the suggestions to refused targets and re-applies the permanent-delete policy, so high-risk suggestions are dropped.
      • Smart Cleaner narrows to refused paths and never asks after a cancelled run.
      • Results passes the scan-time snapshot.
    • Each flow re-checks its navigation or lifetime token after the dialog.
    • Scheduled cleanup has no one to ask, so it keeps the refusal.
    • The batch recycle path retries refusals one at a time, so the flag is set there too.
  • Hard links. The managed and Turbo scanners both persist the flag, and the upsert carries it. Scans have a single root, and visited directories are deduplicated, so the same path cannot be counted twice.
  • Strings. The new keys exist in en-US, de-DE and es-ES, and the XAML resources the banner uses exist.

Remaining notes (judgement calls, not changed)

  • Neither the new banner nor the new dialog has been looked at on screen, by me or by the author. Both compile, and both use existing controls.
  • The refusal dialog lists up to 200 paths, then says "…and N more". The question states the full count.
  • File ids that are not unique but are not a placeholder can still fold unrelated files together. Only the displayed totals would be affected; no deletion decision uses these ids. Pinning this down further would need link counts or 128-bit ids from both scanners.
  • As with every schema bump, an older StorageMaster refuses to open a v16 database.

🤖 Generated with Claude Code

@0langa
0langa merged commit 7643d26 into main Oct 14, 2026
1 check passed
@0langa
0langa deleted the r3/duplicates-safety branch October 14, 2026 21:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant