Skip to content

fix(library): clean orphaned provisional items - #76

Merged
Quick104 merged 7 commits into
mainfrom
fix/library-delete-orphan-metadata-worktree
Jun 8, 2026
Merged

Quick104 merged 7 commits into
mainfrom
fix/library-delete-orphan-metadata-worktree

Conversation

@zZebrahz

@zZebrahz zZebrahz commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Prevent library deletion from leaving late-created provisional media items by deleting orphaned items after membership removal.
  • Harden metadata skeleton creation around disabled/deleted libraries and failed file/membership linking.
  • Add a conservative Goose cleanup migration plus a manual cleanup_orphaned_media_items admin task for installs where the original libraries no longer exist.

Root Cause

A library delete could disable and queue the library while in-flight metadata workers still had already-claimed work. The delete job removed existing orphaned items before deleting the remaining membership rows, so a worker that created an unmatched skeleton during that window could lose its file and library membership later without a second orphan sweep. Stale external IDs then remained because their parent media_items row was never deleted.

Validation

  • go test ./internal/catalog ./internal/taskmanager ./internal/taskmanager/tasks ./internal/metadata ./internal/scanner ./migrations
  • go test ./internal/... ./migrations ./scripts/backfill-library-matching

Notes

  • go test ./cmd/silo cannot run in the fresh worktree until web/dist exists for the frontend embed.
  • The manual cleanup task is intentionally unscheduled and deletes only detached provisional rows with no files, library memberships, or durable user/sync references.

AI Use

Implemented with OpenAI Codex.

Summary by CodeRabbit

  • New Features

    • Added an automated cleanup task and a DB migration to remove orphaned provisional media items.
  • Bug Fixes

    • Improved folder deletion to more reliably identify and clean orphaned content during membership removal.
    • Strengthened metadata operations to roll back partially-created items and avoid inconsistent links.
    • File update now reports missing files when no row is affected.
  • Tests

    • Added unit tests covering cleanup logic and skeleton-creation failure scenarios.

@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c7dfe4d8-ce57-4146-8776-028bcb33e981

📥 Commits

Reviewing files that changed from the base of the PR and between 49ad1a1863740be40daae851a30cc3cd6e1b9db9 and 2d922c3.

📒 Files selected for processing (5)
  • cmd/silo/main.go
  • internal/catalog/folder_delete_test.go
  • internal/catalog/folder_repo.go
  • internal/catalog/orphan_cleanup.go
  • internal/catalog/orphan_cleanup_test.go
💤 Files with no reviewable changes (4)
  • internal/catalog/orphan_cleanup_test.go
  • internal/catalog/folder_delete_test.go
  • internal/catalog/orphan_cleanup.go
  • internal/catalog/folder_repo.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/silo/main.go

📝 Walkthrough

Walkthrough

This PR implements comprehensive cleanup of orphaned provisional media items: a new OrphanedProvisionalCleaner with SQL predicate and batched deletes, folder-delete late-orphan handling, skeleton-creation revalidation and cleanup on failure, a CleanupOrphanedMediaItemsTask with tests, and a DB migration.

Changes

Orphaned Provisional Media Items Cleanup

Layer / File(s) Summary
Orphan cleaner SQL and batched cleanup logic
internal/catalog/orphan_cleanup.go
New OrphanedProvisionalCleaner and SQL predicate that identify provisional-status media_items lacking durable references and delete them in configurable batches via transactional CTEs.
Folder deletion late-orphan handling
internal/catalog/folder_repo.go, internal/catalog/folder_delete_test.go
FolderRepository.DeleteWithStats delays image-dir filtering until after membership deletions; adds helpers to iteratively delete late memberships, delete newly orphaned provisional items, and collect late orphan counts and image dirs; tests assert predicate inclusion.
Skeleton creation safety and file update reporting
internal/metadata/service.go, internal/scanner/file_repo.go, internal/metadata/service_test.go
Adds metadataItemDeleteRepo, re-validates folder under dedup lock, clears file content_id and deletes created skeletons on failure (repo delete or DB fallback); UpdateContentID now returns ErrFileNotFound when no row matched; tests and fakes updated to cover failure/disable scenarios.
Cleanup task framework and test coverage
internal/taskmanager/tasks/cleanup_orphaned_media_items.go, internal/taskmanager/tasks/cleanup_orphaned_media_items_test.go
New CleanupOrphanedMediaItemsTask delegates to the cleaner, reports progress and JSON result data with candidate/deleted counts, handles no-config and error cases; tests cover nominal, no-candidates, and error paths.
Task manager integration and DB migration
cmd/silo/main.go, migrations/sql/20260607220000_cleanup_orphaned_provisional_items.sql
Registers the cleanup task during worker initialization constructed with OrphanedProvisionalCleaner backed by the DB pool; adds a Goose migration that deletes orphaned provisional media_items per the durable-reference predicate (Down noted as non-reversible).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.76% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main objective of the pull request: cleaning up orphaned provisional media items left behind after library deletion.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/library-delete-orphan-metadata-worktree

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@zZebrahz

zZebrahz commented Jun 7, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@zZebrahz

zZebrahz commented Jun 7, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/metadata/service_test.go`:
- Around line 84-89: The fakeItemRepo.Delete implementation currently returns a
formatted error when an item is missing; change it to return the sentinel error
catalog.ErrItemNotFound so callers using errors.Is(err, catalog.ErrItemNotFound)
will match. Update the branch in fakeItemRepo.Delete that checks if _, ok :=
r.items[contentID]; !ok to return nil, catalog.ErrItemNotFound (preserving the
mutex handling) so tests and service cleanup paths behave like production.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b1cb0bc2-45bd-49b4-ad75-852e61b2faad

📥 Commits

Reviewing files that changed from the base of the PR and between 0c5ec1f34bbf0c26bdba6e248b80c4f1e3e30c13 and 49ad1a1863740be40daae851a30cc3cd6e1b9db9.

📒 Files selected for processing (9)
  • cmd/silo/main.go
  • internal/catalog/folder_repo.go
  • internal/catalog/orphan_cleanup.go
  • internal/metadata/service.go
  • internal/metadata/service_test.go
  • internal/scanner/file_repo.go
  • internal/taskmanager/tasks/cleanup_orphaned_media_items.go
  • internal/taskmanager/tasks/cleanup_orphaned_media_items_test.go
  • migrations/sql/20260607220000_cleanup_orphaned_provisional_items.sql

Comment thread internal/metadata/service_test.go Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 49ad1a1863

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@zZebrahz

zZebrahz commented Jun 7, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 82a7373383

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Quick104
Quick104 force-pushed the fix/library-delete-orphan-metadata-worktree branch from f799e61 to d8975d2 Compare June 7, 2026 23:37
@zZebrahz
zZebrahz marked this pull request as ready for review June 8, 2026 00:16

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d8975d234b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/catalog/folder_repo.go Outdated
Comment on lines +721 to +724
const deleteOrphanedProvisionalIDsByContentIDSQL = `
DELETE FROM public.media_items mi
WHERE mi.content_id = ANY($1)
AND ` + orphanedProvisionalMediaItemConditions

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Delete matched items created after the first orphan sweep

When an in-flight matcher passes the enabled-library checks just before the delete request disables the library, it can still insert the skeleton membership after Phase 1 has already swept orphans and then enrich the item to matched before Phase 3 deletes that membership. This late cleanup only re-deletes rows matching orphanedProvisionalMediaItemConditions (pending, unmatched, ambiguous), so the now-detached matched row and its external IDs survive the library deletion—the same stale catalog state this path is trying to prevent.

Useful? React with 👍 / 👎.

@zZebrahz
zZebrahz marked this pull request as draft June 8, 2026 00:20
@zZebrahz
zZebrahz marked this pull request as ready for review June 8, 2026 00:55
@Silo-Server Silo-Server deleted a comment from chatgpt-codex-connector Bot Jun 8, 2026
@zZebrahz

zZebrahz commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@zZebrahz

zZebrahz commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

This was to cover a bug that I found when deleting libraries, It should not happen again but it also added a "Clean Orphaned Media Items" scheduled task that is by default not scheduled (only run manually). This should be safe to run any time but I felt that it should be used ad-hoc and not scheduled. What do you think @Quick104?
image

Other than that, I believe this LGTM, I ran multiple adversarial reviews.

@Quick104
Quick104 merged commit e3ca1ca into main Jun 8, 2026
1 check passed
@Quick104
Quick104 deleted the fix/library-delete-orphan-metadata-worktree branch June 8, 2026 01:32
Quick104 pushed a commit that referenced this pull request Jun 11, 2026
* fix(library): clean orphaned provisional items

* test(metadata): use item not found sentinel in fake repo

* fix(library): preserve abs references during orphan cleanup

* fix(library): avoid dropped abs cleanup tables

* fix(library): harden provisional orphan cleanup

* fix(library): preserve home dismissal series orphans

* fix(library): Delete matched items created after the first orphan sweep
Quick104 pushed a commit that referenced this pull request Jun 17, 2026
* fix(library): clean orphaned provisional items

* test(metadata): use item not found sentinel in fake repo

* fix(library): preserve abs references during orphan cleanup

* fix(library): avoid dropped abs cleanup tables

* fix(library): harden provisional orphan cleanup

* fix(library): preserve home dismissal series orphans

* fix(library): Delete matched items created after the first orphan sweep
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.

2 participants