Skip to content

fix(collections): write no synced items under a collection deleted meanwhile - #4066

Merged
Quick104 merged 1 commit into
Silo-Server:mainfrom
rangoDJ:fix/collection-replace-after-delete-2844
Nov 13, 2026
Merged

Quick104 merged 1 commit into
Silo-Server:mainfrom
rangoDJ:fix/collection-replace-after-delete-2844

Conversation

@rangoDJ

@rangoDJ rangoDJ commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #2844
Related issue: #2615
Validation tasks: none

Other clients: Apple N/A (the orphan rows never reach the API); Android N/A (same); Roku N/A (same)

A personal synced list (MDBList or TMDB) could leave item rows behind for a collection that no longer exists. If the collection, or the profile that owns it, was deleted while a sync of it was in flight, the sync's ReplaceCollectionItems waited for the delete and then inserted the whole list into user_personal_collection_items under the deleted collection's ID. Nothing removed those rows, and the delete reported success.

lockCollectionRow runs SELECT ... FOR UPDATE through Exec, which succeeds when no row matches, and user_personal_collection_items has no foreign key to the collection.

This PR has no dependencies and can merge in any order. #2615, which the issue said to wait for, is merged.

Approach

  • New lockExistingCollectionRow reads the locked row and answers userstore.ErrCollectionNotFound when there is none, also when the lock waited on a delete that then committed. ReplaceCollectionItems uses it and writes nothing for a collection that is gone, as lockLibraryCollectionParent does for library collections.
  • The sync records the failure as it records any other replace error.
  • Delete and reorder keep lockCollectionRow, so deleting a missing collection behaves as before.

Validation

  • gofmt, go vet, and the changed-package lint are clean.
  • go test passes for internal/userstore/pgstore and internal/usercollections against a migrated Postgres 18.6 test database, and the replace tests pass with -race.
  • New DB test TestPostgresReplaceCollectionItemsWaitsOutADelete, added to scripts/ci/db-contracts.txt: a transaction deletes the collection the way deleteCollection does, a replace from another session waits on its lock (checked in pg_stat_activity), and the delete commits. With lockCollectionRow put back, the replace returns nil.
  • Not run: a real MDBList or TMDB sync racing a delete on a running server, and make test-db-contracts.

Evidence

No visible layout change: the orphan rows are invisible in the API. The evidence is the new DB test, on WSL2 (Ubuntu, go1.26.4 linux/amd64) with Postgres 18.6, main at 0387303d9 and this PR at 04c66e51e. "Before" is the same test with the replace locking through lockCollectionRow, as on main.

Replace result after the delete commits Item rows under the deleted ID
Before (main's lock) nil not counted: the test stops at the result (the issue's run found them)
After (this PR) ErrCollectionNotFound 0
$ go test -count=1 -run TestPostgresReplaceCollectionItemsWaitsOutADelete ./internal/userstore/pgstore/   # before
    collection_replace_items_test.go:110: replace after the delete = <nil>, want ErrCollectionNotFound
FAIL

$ go test -count=1 -race -v -run TestPostgresReplaceCollectionItems ./internal/userstore/pgstore/   # after
--- PASS: TestPostgresReplaceCollectionItemsWritesOnlyTheDifference (0.19s)
--- PASS: TestPostgresReplaceCollectionItemsWaitsOutADelete (0.15s)
ok  	github.com/Silo-Server/silo-server/internal/userstore/pgstore	1.501s

Risks

  • A sync whose collection was deleted mid-run now logs a failed sync where it used to report success. The collection is gone, so no user sees that state.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or how I checked a change nobody sees.

AI Disclosure

  • Harness: Claude Code (Claude desktop app, Code tab)
  • Tool(s): Claude Code; GitHub CLI
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: n/a

🤖 Generated with Claude Code

Note

Fix ReplaceCollectionItems to skip writes when collection is deleted concurrently

  • Adds lockExistingCollectionRow, which selects and locks the collection row for the current user. It maps pgx.ErrNoRows to userstore.ErrCollectionNotFound and wraps other query errors with the collection ID (collection_mutations.go).
  • ReplaceCollectionItems now uses this helper, so a replace that waits on a deletion transaction returns userstore.ErrCollectionNotFound before writing item rows. This matters because collection items have no foreign key to the collection, so rows could otherwise be orphaned under a deleted ID (collections.go).
  • Adds a database regression test covering the concurrent delete/replace case (collection_replace_items_test.go) and lists it in the CI database-contract tests (db-contracts.txt).

Macroscope summarized 04c66e5.

…anwhile

A list sync's ReplaceCollectionItems locked the collection row with a
statement that succeeds when no row matches. When it waited on a delete
of the collection, or of its profile, it went on after the delete
committed and inserted the whole list under the deleted ID. The items
have no foreign key to the collection, so nothing removed them.

The replace now locks the row with a read that answers
ErrCollectionNotFound when the row is gone, also after waiting out the
delete, and writes nothing.

Closes Silo-Server#2844

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Nov 13, 2026
@silo-kody

silo-kody Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Collection item replacement now checks for an existing collection row before changing membership. A PostgreSQL concurrency test verifies that replacement returns ErrCollectionNotFound after a concurrent deletion commits and leaves no item rows for the deleted collection.

Changes: Collection replacement and deletion

Layer / File(s) Summary
Require an existing collection before replacement
internal/userstore/pgstore/collection_mutations.go, internal/userstore/pgstore/collections.go, internal/userstore/pgstore/collection_replace_items_test.go, scripts/ci/db-contracts.txt
ReplaceCollectionItems locks an existing collection row before changing membership. If a concurrent delete commits while replacement waits, replacement returns ErrCollectionNotFound. The PostgreSQL test checks that no item rows remain, and the CI database-contract list includes the test.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: rhainland, quick104

Merge Risk: Minimal · up to 04c66

Replacing items for a collection deleted mid-sync now returns a not-found error instead of writing orphan rows. No actionable merge-blocking risk remains.

Security architecture risk: Minimal · up to 04c66

The change closes a deletion race without expanding access or write authority. Replacement now verifies that the collection still exists before changing membership, and the failure path cannot recreate a deleted collection. No material security risk was found introduced or worsened by this PR.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The changed write decision concerns membership for one collection within the store's bound account. The PR does not broaden which account or collection the writer can target; it removes the ability of this path to proceed after its parent disappears.

Trust Boundaries and Controls

  • observed — Source-derived titles pass through the existing owner-access resolution and accessible-title selection before reaching membership replacement. RunSync documents caller responsibility for collection ownership. This PR changes neither that responsibility nor the owner-filtering flow.

Resilience and Maintainability Implications

  • inferred — Replacement and collection/profile deletion serialize on the parent collection row. A committed deletion prevents subsequent replacement writes; if replacement wins first, deletion waits and then removes its membership. A rolled-back deletion leaves a parent available to replacement. Membership differences remain in one transaction with deferred rollback and one commit, preserving partial-failure containment and repeat-call behavior.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: a sync's replace of items for a collection deleted mid-flight now writes no synced items. It matches the locking change in ReplaceCollectionItems and the new ErrCollec…
Description check Passed The description states the problem (orphan item rows left under a deleted collection), the approach (lockExistingCollectionRow for replace only), validation steps, and a before/after test table. It re…
Linked Issues check Passed Issue #2844 requires that replacing items for a personal collection that no longer exists writes nothing and returns a not-found error, including when the replace waits on a delete. At head, `lockExis…
Out of Scope Changes check Passed The changes stay within #2844. The new helper and its doc comment (collection_mutations.go), the 3-line switch in ReplaceCollectionItems (collections.go), and the new DB test (`collection_replac…
Full details: Title check

Explanation

The title names the main change: a sync's replace of items for a collection deleted mid-flight now writes no synced items. It matches the locking change in ReplaceCollectionItems and the new ErrCollectionNotFound path. It is conventional-commit style and specific enough for a teammate scanning history.

Full details: Description check

Explanation

The description states the problem (orphan item rows left under a deleted collection), the approach (lockExistingCollectionRow for replace only), validation steps, and a before/after test table. It relates directly to the changeset.

Full details: Linked Issues check

Explanation

Issue #2844 requires that replacing items for a personal collection that no longer exists writes nothing and returns a not-found error, including when the replace waits on a delete. At head, lockExistingCollectionRow in internal/userstore/pgstore/collection_mutations.go runs the same SELECT 1 ... FOR UPDATE as lockCollectionRow, but maps pgx.ErrNoRows to userstore.ErrCollectionNotFound. The row lock waits on a concurrent delete. After that delete commits, the locking query returns no row, so the helper returns the not-found error. Per the PR summary, ReplaceCollectionItems in collections.go calls this helper before any item write, so no item rows are inserted for a deleted collection. A profile delete removes the same collection rows, so the same lock path covers the owning-profile case. Delete and reorder keep lockCollectionRow, which the issue does not require to change. The new DB test TestPostgresReplaceCollectionItemsWaitsOutADelete covers the wait-then-not-found case. The author reports that it fails on the prior lock and passes with this change. I did not re-run the test. The test and the helper are consistent with the issue's expected behavior.

Full details: Out of Scope Changes check

Explanation

The changes stay within #2844. The new helper and its doc comment (collection_mutations.go), the 3-line switch in ReplaceCollectionItems (collections.go), and the new DB test (collection_replace_items_test.go) all address the replace-after-delete race. The one-line addition to scripts/ci/db-contracts.txt registers the new test in the database contract list. The sync records the replace error as it records other replace errors, so no unrelated sync behavior changes. No unrelated change was identified in the reviewed evidence. I read the head file for collection_mutations.go directly. The collections.go, test, and CI list changes rest on the PR summary and were not separately read.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 39347233-e6d2-4fda-9153-5d72f3d342bf
Commits

Reviewing files that changed from the base of the PR and between 7edef3d and 04c66e5.

Files selected for processing: 4

  • internal/userstore/pgstore/collection_mutations.go
  • internal/userstore/pgstore/collection_replace_items_test.go
  • internal/userstore/pgstore/collections.go
  • scripts/ci/db-contracts.txt

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels Nov 13, 2026
@Quick104

Copy link
Copy Markdown
Contributor

🤖 Claude Code (claude-opus-5-5)

Review of 04c66e5: no findings. The fix is correct and as small as it can be. Fit: 9/10 · Readiness: 9/10 — ready.

Defect confirmed on main. lockCollectionRow runs SELECT ... FOR UPDATE through Exec, which succeeds on zero rows, and user_personal_collection_items has no foreign key to the collection. I ran TestPostgresReplaceCollectionItemsWaitsOutADelete against a freshly migrated Postgres 18 database:

  • With ReplaceCollectionItems locking through lockCollectionRow, as on main, the replace returns nil and leaves 2 item rows under the deleted collection's ID. I made the error check non-fatal for this run so the test would also count the orphan rows.
  • On this head, the replace returns ErrCollectionNotFound and leaves 0 rows. TestPostgresReplaceCollectionItemsWritesOnlyTheDifference still passes, and both pass under -race.

What I checked

  • Under READ COMMITTED, a FOR UPDATE that waits on a row deleted by the transaction it waited for returns no row once that transaction commits. This holds for a single collection delete and for a profile delete's bulk DELETE ... RETURNING id.
  • Lock order is unchanged. The replace takes the same row lock at the same point, so the deadlock reasoning in the lockCollectionRow comment still applies.
  • Keeping delete and reorder on the old helper is the right split. Changing lockCollectionRow itself would make deleting a missing collection fail where it now succeeds.
  • RunSync records the error through its existing fail path. That writes an UPDATE matching zero rows, which is harmless. In the rare race, a manual sync now answers 500 "collection not found" where it used to report success over orphan rows. Either way the collection is already gone.
  • The SQLite store already rejects sync replaces, and no conformance test expects success for a missing collection.
  • An independent cross-provider round (Codex, gpt-6.1-sol, one round on this head) found nothing introduced by this PR.

Validation: no passed case on the v1.0 board covers synced personal lists. Collections — Server (#193) S2 covers manual add, remove, reorder, and delete, which this PR doesn't change. Validation tasks: none is correct.

User manual: unaffected. Other clients: N/A, as the PR says; no response shape changes.

Fit 9/10: a narrow data-integrity fix at the store boundary that owns the lock, and it matches what the library-collection path already does. Readiness 9/10: the new test fails on main's locking and passes here, and CI is green.

@Quick104
Quick104 merged commit 8eb38fa into Silo-Server:main Nov 13, 2026
18 checks passed
@rangoDJ
rangoDJ deleted the fix/collection-replace-after-delete-2844 branch November 15, 2026 00:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/M 50–199 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] A personal list sync that races a collection delete leaves orphan item rows

2 participants