Skip to content

perf(collections): write only membership changes when a list syncs - #2615

Merged
Quick104 merged 3 commits into
Silo-Server:mainfrom
Rhainland:perf/collection-sync-replace-items
Oct 21, 2026
Merged

Quick104 merged 3 commits into
Silo-Server:mainfrom
Rhainland:perf/collection-sync-replace-items

Conversation

@Rhainland

@Rhainland Rhainland commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

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) or created_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) and LibraryCollectionRepository.ReplaceItems (library lists) now run three bulk statements in one transaction, using unnest arrays: 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, so added_at and created_at survive 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_at only when membership changed. The personal replace now locks the collection row first, following the lock order documented on lockCollectionRow, 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 (UpdateCollectionSyncState for personal lists, RecordSyncRun for 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

  • New DB tests for both stores cover unchanged, reordered, grown, shrunk, emptied, and duplicate lists. They check order, rank, kept added_at/created_at, and whether the revision advanced. They fail against the old code.
  • Both replaces lock the collection's current members before their first write, so a concurrent media item delete or provider-ID merge cannot deadlock with them. TestLibraryCollectionReplaceItemsRacesMemberDeleteDB stages that race for library lists. It fails with a deadlock without the member lock. The new DB tests are listed in scripts/ci/db-contracts.txt, so CI runs them.
  • Focused DB-backed tests for catalog, userstore, usercollections, sections, userdb, and the collection handlers pass.
  • Pre-PR gate from CONTRIBUTING.md: build, gofmt, go vet, make lint-changed, lint-router-recovery, the verify-* targets, and the web lint, format, build, and budget checks pass. verify-shellcheck was 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: TestHandleStartPlaybackV3DoesNotWaitForSessionSync and two TestPlaybackInfo… 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.
  • Benchmark: a 12,000-title synthetic catalog, a local fake MDBList upstream, and lists of 200 to 10,000 titles. The same binary built with and without this change, with the list size limit lifted locally so lists above 500 titles could be imported. Statements are counted with pg_stat_statements (track=all, so nested trigger and foreign-key statements count too).
Before/after statements and time per sync
Titles Path Statements before Statements after ms before ms after
200 personal import 769 231 119 75
200 personal re-sync 751 27 109 63
200 library import 1,022 451 139 90
200 library re-sync 927 29 136 69
1,000 personal import 3,493 1,034 306 136
1,000 personal re-sync 3,476 28 293 115
1,000 library import 4,544 2,047 328 163
1,000 library re-sync 4,626 29 316 123
4,500 personal import 15,467 4,532 1,251 401
4,500 personal re-sync 15,271 31 1,197 292
4,500 library import 20,055 9,084 1,292 429
4,500 library re-sync 19,842 68 1,338 351
10,000 personal import 30,138 10,036 4,054 737
10,000 personal re-sync 30,062 31 3,129 580
10,000 library import 40,101 20,168 3,550 955
10,000 library re-sync 40,167 34 3,115 746

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}/items for 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's added_at moves 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_at in 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

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code
  • Tool(s): Claude Code; Codex CLI (second reviewer)
  • Model(s): claude-opus-5-5; gpt-6.1-sol (review only)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: independent reviews of the full diff by claude-opus-5-5 and gpt-6.1-sol, reconciled; neither reported findings.

Note

Write only membership changes when a collection syncs

  • Reworks LibraryCollectionRepository.ReplaceItems and PostgresUserStore.ReplaceCollectionItems from 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.
  • Retained items keep their created_at/added_at timestamps, and the collection revision and updated_at now change only when membership actually differs.
  • Adds database contract tests covering unchanged, reordered, grown, shrunk, emptied, and duplicate replacements, plus a test where replacement races a media item deletion and must not return a PostgreSQL deadlock (40P01). Tests skip unless SILO_TEST_DATABASE_URL is set.
  • Registers the new tests in db-contracts.txt.
  • Behavioral Change: concurrent replacements serialize through the collection lock instead of row rewrites; a replacement racing a member deletion can still fail with the existing foreign-key error.

Macroscope summarized c566917.

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-triage silo-triage Bot added the size/L 200–499 added + deleted lines (all files); change volume, not priority. label Oct 16, 2026
@silo-kody

silo-kody Bot commented Oct 16, 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 Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9e8178cc-10e9-4980-ad5d-61c6c523081b
📥 Commits

Reviewing files that changed from the base of the PR and between 6cf8e5d and c566917.

📒 Files selected for processing: 4
  • internal/catalog/library_collection_replace_items_db_test.go
  • internal/catalog/library_collection_repo.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; 0 remain after this review.

📝 Walkthrough

Both collection replacement methods now deduplicate inputs and apply membership changes as a difference. Unchanged members retain their timestamps. Database tests cover ordering, metadata, revision behavior, and concurrent deletion handling.

Changes: Collection membership replacement

Layer / File(s) Summary
Library collection membership diff
internal/catalog/library_collection_repo.go, internal/catalog/library_collection_replace_items_db_test.go, scripts/ci/db-contracts.txt
ReplaceItems deduplicates inputs, deletes removed rows, updates changed positions or source ranks, and inserts new rows. It updates collection timestamps only when membership rows change. Database tests cover ordering, ranks, timestamps, revisions, and concurrent deletion.
User collection membership diff
internal/userstore/pgstore/collections.go, internal/userstore/pgstore/collection_replace_items_test.go, scripts/ci/db-contracts.txt
ReplaceCollectionItems deduplicates inputs, locks the collection and existing members, and applies membership changes with set-based statements. It preserves unchanged rows and their added_at values. PostgreSQL tests cover ordering, revisions, timestamps, and duplicate inputs.

Priority: ⬇️ Low

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Suggested reviewers: quick104, coffeeknyte

Merge Risk: ⚪ Minimal · up to c5669

No additional issue is confirmed from this review. The change is mergeable after the usual checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 4 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely summarizes the main change: collection syncs now write only membership differences.
Description check Passed The description directly explains the performance optimization, preserved timestamps, transactional diff behavior, locking changes, tests, validation, and known limitations.
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 4 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • 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

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

@silo-triage silo-triage Bot added enhancement New feature or request go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish triaged High-confidence review completed; does not mean fixed, validated, or accepted for release. labels Oct 16, 2026
@macroscopeapp

macroscopeapp Bot commented Oct 16, 2026

Copy link
Copy Markdown
  • internal/userstore/pgstore/collections.go: synced personal collection items now retain their original added_at in GET /api/v2/collections/{id}/items instead of reporting the latest sync time; add before-and-after response excerpts for the same request and identify the API surface and build/commit.

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

silo-kody Bot commented Oct 17, 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 ❌

@Quick104 Quick104 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.

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>
@Quick104

Copy link
Copy Markdown
Contributor

Review summary

Reviewed 42a827a. Fixes are pushed in c566917.

Addressed

  • A sync could deadlock with a concurrent media item delete or provider-ID merge, because the DELETE's trigger took the collection revision before the UPDATE reached the member rows. Both replaces now lock the current members right after the parent lock, which is the order the old delete-all used. A new DB test stages the race for library lists. It deadlocked on 3 of 3 runs at 42a827a and passes now. The personal variant was found by tracing the code, not reproduced.
  • The new DB tests are now in scripts/ci/db-contracts.txt, so CI runs them.

Verification

  • Both original tests fail on the base (df107b7) and pass on the head. The race test fails on 42a827a and passes on c566917.
  • The focused catalog, pgstore and usercollections tests pass against a migrated Postgres 18. One exception: TestCollectionCollageReadsKeepActiveVariantsDB fails on that host with or without this PR, because of clock skew between the test client and the database.
  • EXPLAIN under force_generic_plan on a 10,000-member collection shows a hash anti-join for the departed-member delete, so the earlier generic-plan concern is settled.
  • A second review by another model (gpt-6.1-sol) found nothing new.

Left for the maintainers

  • The sync-state writes after each sync still advance the revision, as the PR body says. Unchanged re-syncs therefore still invalidate cursors and rail caches. Fixing that is a contract decision for a separate change.
  • Pre-existing: a personal sync that races a collection delete inserts orphan item rows. It happens on main too, so it's filed as [bug] A personal list sync that races a collection delete leaves orphan item rows #2844 to follow this PR.

Validated features: none of the passed cases on the v1.0 board touch collection sync. Validation tasks: none is correct.

Ordering with #2621: the PRs share no files. This PR updates position in place, and each UPDATE that changes rows advances the revision through the item trigger, so #2621's revision fence still sees the change. They can merge in either order.

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 added_at on personal list items stays stable across re-syncs, and no first-party client renders it.

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)

  • Fit: it makes scheduled list syncs cheap at any list size without new settings or surface area. That matters most on small hosts and in clusters that sync many lists.
  • Readiness: the approach is sound, and the confirmed defect is fixed. Every behavior change is covered by a test that fails without it, and the tests now run in CI.

@silo-triage silo-triage Bot added size/XL 500–999 added + deleted lines (all files); change volume, not priority. and removed size/L 200–499 added + deleted lines (all files); change volume, not priority. labels Oct 21, 2026
@silo-kody

silo-kody Bot commented Oct 21, 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 ❌

Comment on lines +791 to +796
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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug high

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.

​

​

@Quick104
Quick104 merged commit ea2570c into Silo-Server:main Oct 21, 2026
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/XL 500–999 added + deleted lines (all files); change volume, not priority. triaged High-confidence review completed; does not mean fixed, validated, or accepted for release.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants