Repository navigation
perf(collections): write only membership changes when a list syncs - #2615
Conversation
A list sync replaced a collection's membership with one INSERT per title, and each INSERT fired the statement-level revision trigger. A re-sync of an unchanged 10,000-title list cost about 30,000 to 40,000 statements and 3 s, rewrote every added_at/created_at, and advanced the collection revision once per title. ReplaceCollectionItems and LibraryCollectionRepository.ReplaceItems now write only the difference in one transaction: a bulk DELETE of titles that left, a bulk UPDATE of titles whose position (and source rank) changed, and a bulk INSERT of new titles. Titles that stay keep added_at/created_at, and an unchanged list writes no item rows, so the item triggers leave the revision alone. The library replace touches library_collections.updated_at only when membership changed. The personal replace now locks the collection row first so concurrent replaces of one collection cannot interleave.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
📝 Walkthrough
Merge Risk: ⚪ Minimal · up to
|
Suggested fix: Add those excerpts under Evidence. Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness. Posted via Macroscope — Visible change evidence |
The membership-diff DELETE filtered with NOT (id = ANY($ids)). Under a generic plan the array is a parameter, so PostgreSQL scans it linearly for every existing member. Use NOT EXISTS over unnest($ids), which plans as a hash anti-join in both the library and the personal replace.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
Quick104
left a comment
There was a problem hiding this comment.
Review of 42a827a. Three findings below. The approach holds up: both new tests fail on the base and pass on this head, and an EXPLAIN under force_generic_plan on a 10,000-member collection shows a hash anti-join for the delete. I'm fixing all three in a commit on this branch, so there's no need to change anything yourself.
The set-based replace takes the collection revision row in the DELETE's statement trigger and only then reaches the rows it updates. A media item delete (FK cascade) or a provider-ID merge locks a member row first and the revision second, so the two could deadlock. Lock the current members right after the parent lock, as the old delete-all did, and add the new DB tests to the contracts list so CI runs them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review summaryReviewed 42a827a. Fixes are pushed in c566917. Addressed
Verification
Left for the maintainers
Validated features: none of the passed cases on the v1.0 board touch collection sync. Ordering with #2621: the PRs share no files. This PR updates User manual: unaffected. The collections pages on siloserver.org don't describe membership dates or sync cost. Apple/Android: no parity work. The only client-visible change is that Evidence: the published page still matches. The lock change doesn't alter what it shows. Fit: 9/10 · Readiness: 9/10 — ready (assuming CI is green)
|
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
| if _, err := tx.Exec(ctx, ` | ||
| SELECT 1 FROM library_collection_items | ||
| WHERE collection_id = $1 | ||
| ORDER BY media_item_id | ||
| FOR UPDATE | ||
| `, collectionID); err != nil { |
There was a problem hiding this comment.
Deadlock remains possible during provider-ID merges: the ordered prelock in internal/catalog/library_collection_repo.go can lock source member a and wait for canonical member b, while mediaItemMergeSteps in provider_id_integrity.go first locks b through its collection upsert and then waits for a during source-item deletion. Even an unchanged replacement can now deadlock, whereas the previous difference-only statements locked neither unchanged member; coordinate member-lock ordering with the merge path rather than enforcing it only for replacements.
Prompt for LLM
File internal/catalog/library_collection_repo.go:
Line 791 to 796:
Deadlock remains possible during provider-ID merges: the ordered prelock in `internal/catalog/library_collection_repo.go` can lock source member `a` and wait for canonical member `b`, while `mediaItemMergeSteps` in `provider_id_integrity.go` first locks `b` through its collection upsert and then waits for `a` during source-item deletion. Even an unchanged replacement can now deadlock, whereas the previous difference-only statements locked neither unchanged member; coordinate member-lock ordering with the merge path rather than enforcing it only for replacements.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
Problem
Related issue: N/A
Validation tasks: none
Every MDBList or TMDB list sync rewrote the whole collection one title at a time, whether or not the list had changed. A scheduled re-sync of an unchanged 10,000-title list took about 3 s and 30,000 to 40,000 SQL statements, as much as the first import, on every run of every synced list. It also reset each member's
added_at(personal) orcreated_at(library) to the sync time, and advanced the collection revision once per title.This change writes only the difference. An unchanged re-sync now runs about 30 statements at any list size and keeps the dates titles were added.
Approach
ReplaceCollectionItems(personal lists) andLibraryCollectionRepository.ReplaceItems(library lists) now run three bulk statements in one transaction, usingunnestarrays: delete the titles that left, update the titles whose position (and, for library lists, source rank) changed, and insert the new titles. Titles that stay keep their row, soadded_atandcreated_atsurvive re-syncs. Duplicates still resolve to the first occurrence, and library positions stay dense.Revisions: the item revision triggers are statement-level and read the transition tables, so a statement that changes no rows does not advance the revision. A reorder, addition, or removal advances it as before. The library replace touches
library_collections.updated_atonly when membership changed. The personal replace now locks the collection row first, following the lock order documented onlockCollectionRow, so two replaces of the same collection cannot interleave. Both replaces then lock the collection's current members before writing, the lock order the old delete-all had, so a concurrent media item delete or provider-ID merge cannot deadlock with them.What this does not change: the sync-state write that follows every sync (
UpdateCollectionSyncStatefor personal lists,RecordSyncRunfor library lists) still updates the collection row, and the row trigger advances the revision. That revision also fences definition reads in the collection editor, and the sync status is part of that definition, so a membership cursor taken before a sync still goes stale after it. Changing that is a contract decision for a separate change. Realtime events, collage refresh, and the library sync-run counts are computed by the callers and are unchanged.Validation
added_at/created_at, and whether the revision advanced. They fail against the old code.TestLibraryCollectionReplaceItemsRacesMemberDeleteDBstages that race for library lists. It fails with a deadlock without the member lock. The new DB tests are listed inscripts/ci/db-contracts.txt, so CI runs them.catalog,userstore,usercollections,sections,userdb, and the collection handlers pass.gofmt,go vet,make lint-changed,lint-router-recovery, theverify-*targets, and the web lint, format, build, and budget checks pass.verify-shellcheckwas not run because ShellCheck is not installed locally; the change touches no shell scripts.make test-go(no database, as in CI): three tests fail in the same way on the base commit:TestHandleStartPlaybackV3DoesNotWaitForSessionSyncand twoTestPlaybackInfo…tests in jellycompat. Everything else passes.make test-db-pins: two recommendations pins failed in the batch run and pass when run on their own, on this branch and on the base commit.make test-web: a few admin-page tests time out, and a different set each run (9 tests, then 3 of them on rerun). This branch changes no web files.pg_stat_statements(track=all, so nested trigger and foreign-key statements count too).Before/after statements and time per sync
The first import still counts about one statement per title for personal lists and two for library lists. Those are PostgreSQL's internal foreign-key checks for each row of the single bulk
INSERT, not separate statements from Silo.Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/pr-2615/
Surface: native API,
GET /api/v2/collections/{id}/itemsfor a personal MDBList collection; the web app does not show this field. Main (df107b7) and this branch (42a827a) ran the same steps on the same seeded synthetic catalog, with a local stand-in for MDBList: import a 5-title list, then re-sync it unchanged about 70 seconds later. On main every title'sadded_atmoves to the re-sync time. On this branch every title keeps its import time. Titles, positions and counts are the same on both.Risks
Membership
added_atin the personal collection items API now stays stable across re-syncs instead of moving to the last sync time. Nothing in the web app renders it. No migration, and no API shape change.Checklist
AI Disclosure
Note
Write only membership changes when a collection syncs
LibraryCollectionRepository.ReplaceItemsandPostgresUserStore.ReplaceCollectionItemsfrom delete-all-then-reinsert into a transaction that deduplicates input, locks the collection row and existing members in order, then deletes, updates, or inserts only the rows that differ.created_at/added_attimestamps, and the collection revision andupdated_atnow change only when membership actually differs.SILO_TEST_DATABASE_URLis set.Macroscope summarized c566917.