Skip to content

fix(catalog): stop parallel scans creating duplicate name-only people - #3166

Merged
Quick104 merged 3 commits into
Silo-Server:mainfrom
Rhainland:fix/1253-person-find-or-create-race
Oct 31, 2026
Merged

Quick104 merged 3 commits into
Silo-Server:mainfrom
Rhainland:fix/1253-person-find-or-create-race

Conversation

@Rhainland

@Rhainland Rhainland commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #1253
Validation tasks: changes #1254 C1; changes #1256 C11

A fresh scan can create the same person twice. In a synthetic audiobook library with three books by one author, the first scan stored two "Ada Lane" rows: two books credited one, the third the other. Her author page, the library's Authors view and People search then split her books, and "Also by Ada Lane" misses the book on the other row.

The audiobook scan processes folders in parallel, and PersonRepository.FindOrCreate looked a name up and then inserted it with nothing in between, so two workers that both missed the lookup each inserted a row. Names can't carry a unique index, because different people share names. This change serialises the lookup and insert for one name.

Approach

The name lookup and the insert now run in one transaction behind pg_advisory_xact_lock(hashtextextended('people-name:' || LOWER(name), 0)), following the repo's existing hashtextextended('<namespace>:'||key, 0) locks. The transaction explicitly uses READ COMMITTED so the lookup sees the preceding lock holder's insert even when the connection defaults to REPEATABLE READ. The lock lives in Postgres, so it also holds between Silo replicas sharing one database, and it is held only for one SELECT and one INSERT. Matching still goes through canResolvePersonByName, so namesakes with different provider IDs stay separate. Lookups by TMDB or IMDb ID are unchanged; those columns already have unique indexes.

Ebook scans call the same function and are covered too.

BatchFindOrCreate (metadata ingestion and book enrichment) has the same look-up-then-insert gap for people with no provider ID. Closing it there needs the transaction to span several phases and multi-key locking, so it is left for a follow-up. Existing duplicate rows are not merged; there is no merge tool for name-only people yet.

Validation

  • The Postgres test (listed in scripts/ci/db-contracts.txt) runs 20 rounds of 8 concurrent FindOrCreate calls for one name in mixed case and expects one row. It sets the connection default to REPEATABLE READ to check snapshot visibility after the lock wait. The original test failed on the merge base with eight rows; the enhanced test failed on the unfixed PR head with eight rows. After the isolation fix, the concurrency and namesake-preservation tests pass five runs with -race.
  • Review verification on 7c8e0e354: make test-db-pins (157 query pins and 372 database contracts), catalog/scanner package tests, package vet, and make lint-changed pass against a disposable PostgreSQL 18 database where applicable. This review did not repeat a complete scan through the UI or the full local pre-PR gate.
  • go test ./internal/catalog/... ./internal/scanner/... with a database, make test-db-contracts, make lint-changed: pass.
  • Full gate on an integration build of this branch with the other Audiobooks #1253 fixes: see the summary on Audiobooks #1253.
  • Runtime: the duplicate appeared on one of two fresh base scans of the same library (it is a race). Fresh scans on the fix build produced no duplicate people, and the author page lists all of her books.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/pr-3166/

Postgres test results for 8 concurrent creations of one name-only person: the base commit made 5 people for one name; this branch makes one. In the library, the race shows as one author split into several Authors entries. With this change, the Authors view shows "Ada Lane · 4 books" instead of two separate entries for her.

Risks

None identified. The lock is per name and held briefly; scans that create many different people do not wait on each other.

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 says there is none.

AI Disclosure

  • Harness: Claude Code (T3 Code); OpenAI Codex (T3 Code)
  • Tool(s): Claude Code, Codex CLI, GitHub CLI, Playwright, Docker, ffmpeg
  • Model(s): claude-opus-5-5; gpt-6.1-sol (review and transaction isolation fix)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: GPT 6.1 Sol reviewed the diff, scanner callers, transaction cleanup, tests, contracts and recorded validation cases; Claude Opus 5.5 independently reviewed the source. The reviews identified the test's mixed-case cleanup and a transaction-isolation dependency. Both are fixed. The isolation defect was reproduced with the existing test, the enhanced test failed on the unfixed head, and the final source check found no further defect. The unchanged BatchFindOrCreate gap remains disclosed above.

Note

Fix duplicate name-only people from parallel FindOrCreate scans

  • Parallel calls to catalog.PersonRepository.FindOrCreate with the same name-only person could create duplicate rows. The name fallback now runs through findOrCreateByName in a read-committed transaction, which takes a transaction-scoped advisory lock keyed by the lowercased name before lookup and insert.
  • Extracts the lookup into findPersonByName and the insert into insertPerson; both run through the caller's transaction, and the insert commits with it.
  • Adds TestPersonFindOrCreateConcurrentNameOnlyPostgres in person_name_fallback_db_test.go — 20 rounds of 8 concurrent workers with mixed capitalization, asserting one row and one person ID per round — and registers it in db-contracts.txt.
  • Behavioral Change: insertPerson now writes through the caller's transaction, so insert failures roll back with it; name lookups acquire an advisory lock (personNameLockSQL), which serializes concurrent name-only creates.

Macroscope summarized 7c8e0e3.

FindOrCreate looked a person up by name and then inserted with no lock,
so parallel audiobook and ebook scan workers (or replicas sharing one
database) that all missed the lookup each inserted their own row for the
same author. The author's books then split across namesake people.

Hold a transaction-scoped advisory lock keyed on the lower-cased name
around the name lookup and insert. People may still share a name: the
provider-safe name rules decide whether a stored row matches, the lock
only stops concurrent callers from both missing.
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Oct 27, 2026
@silo-kody

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

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

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: eec320d6-42c3-4423-b979-ae48d9a0e8a4
Commits

Reviewing files that changed from the base of the PR and between 80023e7 and 7c8e0e3.

Files selected for processing: 2
  • internal/catalog/person_name_fallback_db_test.go
  • internal/catalog/person_repo.go

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

Walkthrough

FindOrCreate now uses a transaction and a case-folded advisory lock for name fallback and insertion. A PostgreSQL contract test checks concurrent calls for the same name with different casing.

Changes: Person name fallback

Layer / File(s) Summary
Transactional name fallback
internal/catalog/person_repo.go
FindOrCreate delegates name fallback to a transaction-backed helper. For nonempty names, the helper locks on the case-folded name and searches for a provider-safe match. It commits before enriching a match, or inserts and commits when no match exists.
Concurrent call validation
internal/catalog/person_name_fallback_db_test.go, scripts/ci/db-contracts.txt
The PostgreSQL test runs 20 rounds of eight concurrent name-only calls with alternating casing. It checks for one matching row and identical returned IDs in each round. The database-contract list includes the test.

Priority: Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested labels: impact: usability

Suggested reviewers: blurbery, quick104

Merge Risk: Minimal · up to 7c8e0

Same-name lookups are serialized to prevent duplicate people. No merge-blocking issue was established.

Security architecture risk: Low · up to 7c8e0

The change strengthens concurrent person resolution while preserving provider-identity checks and existing access boundaries. Residual risk is limited to database contention and transaction failure handling. Existing duplicates and batch-ingestion races remain outside its scope.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The added contention domain is same-name resolution among participating connections sharing a database. Waiting requests occupy database connections, but the lock does not extend through post-selection enrichment. The inspected change establishes no expansion of privileges or independently attacker-controlled entrypoints.

Trust Boundaries and Controls

  • observed — The supplied name remains a bound SQL parameter in lock acquisition, candidate lookup, and insertion. The new coordination mechanism does not replace the existing provider-safe identity predicate or introduce caller-selected SQL.

Resilience and Maintainability Implications

  • inferred — For a nonempty name-only request whose commit outcome is uncertain, repeating resolution through the new path reacquires the same lock and looks for a committed compatible row before inserting. This supports recovery without a separate reservation state, although cancellation and ambiguous-commit behavior were not directly tested.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… 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 "fix(catalog): stop parallel scans creating duplicate name-only people" matches the main change. The PR serializes name lookup and insert in PersonRepository.FindOrCreate with a transaction-…
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.
Description check Passed The description is specific and on-topic. It names the bug (duplicate name-only people from parallel audiobook scans), the fix (a transaction-scoped advisory lock keyed by the lowercased name, with RE…
Full details: Title check

Explanation

The title "fix(catalog): stop parallel scans creating duplicate name-only people" matches the main change. The PR serializes name lookup and insert in PersonRepository.FindOrCreate with a transaction-scoped advisory lock keyed by the lowercased name, which prevents duplicate name-only people from parallel scans. The title is specific and follows a conventional commit style.

Full details: Description check

Explanation

The description is specific and on-topic. It names the bug (duplicate name-only people from parallel audiobook scans), the fix (a transaction-scoped advisory lock keyed by the lowercased name, with READ COMMITTED isolation), the scope limits (TMDB/IMDb lookups unchanged, BatchFindOrCreate deferred, existing duplicates not merged), and the validation steps. It relates directly to the changeset, so it passes.

Full details: Docstring Coverage

Explanation

Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 3 functions across 2 files.

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

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

@silo-triage silo-triage Bot added bug Something isn't working evidence-required Needs before-and-after evidence before the Evidence check passes go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels Oct 27, 2026
@silo-triage

silo-triage Bot commented Oct 27, 2026

Copy link
Copy Markdown

This fixes a user-visible change: the body describes duplicate Authors entries becoming one entry with all books. Please replace the no-user-visible-change statement with before-and-after captures of that Authors view using the same synthetic library, identify the builds, and include desktop and phone-width web captures (or explain why mobile is unaffected).

@macroscopeapp

macroscopeapp Bot commented Oct 27, 2026

Copy link
Copy Markdown

The name-only person fix changes which books appear under an author, so the Evidence: none, no user-visible change statement does not cover this visible behavior. Please add before-and-after captures of the same test library’s Authors view and author page, showing the books grouped before and after, and identify the surfaces and builds.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@coderabbitai coderabbitai Bot added the impact: usability Core flow broken or severely blocked label Oct 27, 2026
@macroscopeapp

macroscopeapp Bot commented Oct 27, 2026

Copy link
Copy Markdown

The two cases listed as unblocked (#1254 C1 and #1256 C11) are Not run, so there is no recorded failed or blocked result to unblock. The passed Person/cast & crew results (#1143, #1144, silo-apple #307/#308, and silo-android #317/#318) are unaffected: those actor/director cases use provider-backed Movie/Series credits through BatchFindOrCreate, while this change's name lock addresses direct name-only audiobook/ebook scan writes. For this recorded-results check, the corrected line is Validation tasks: none.

-Validation tasks: unblocks #1254 C1; unblocks #1256 C11
+Validation tasks: none

Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed.

Posted via Macroscope — v1 validation impact

@Rhainland

Copy link
Copy Markdown
Contributor Author

Not adding Authors captures. The race only shows when two scan workers create the same person at the same moment, and I can't reproduce that on demand on a real server. The new concurrency test covers it. A library scanned without the race looks the same before and after, so a before/after pair would show identical screens.

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

Reviewed 80023e74b3d210eb82a91ae0ea4f26a663e876c5. One conditional concurrency defect reproduced against a disposable PostgreSQL database; I am fixing it on this branch.

Note

AI disclosure: OpenAI Codex in T3 Code, model gpt-6.1-sol, using GitHub CLI and Go. Independent source review by Claude, model claude-opus-5-5; its isolation concern was verified by running the existing test on the reviewed head.

Comment thread internal/catalog/person_repo.go Resolved
@silo-kody

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

Copy link
Copy Markdown
Contributor

Fit: 10/10 · Readiness: 9/10 — ready.

CI passed on 7c8e0e354, including the aggregate CI result. All checks have completed with no failures. CodeRabbit reported no actionable findings; its docstring-coverage warning is advisory and its check passed. The validation-impact check completed neutral and found no affected recorded outcome.

Reviewed 80023e74, then pushed the verified repair as 7c8e0e354830749154ee62aadcebe0cb0927bb02. The catalog owns person identity, and the database lock coordinates writers across replicas.

Finding: one P3, fixed in 7c8e0e354. With a connection default of REPEATABLE READ, the advisory-lock statement froze the snapshot before waiting, so the subsequent lookup could miss the preceding insertion. The transaction now explicitly uses READ COMMITTED. No actionable introduced finding remains; no production use of the nondefault isolation was established.

Verification: the original test failed on the merge base with eight rows for one name. The enhanced test failed on the unfixed PR head with eight rows. After the repair, concurrency and namesake-preservation tests passed five runs with -race. All 157 query pins and 372 database contracts passed, along with catalog/scanner package tests, package vet, and changed-line lint. The full local pre-PR gate and UI/device checks were not repeated in this review. The disposable database and tunnel were removed.

Validated features: source tracing found no regression to these accepted Movie/Series person cases; their provider-backed credits use the existing batch ingestion path.

Recorded cases Validated build Classification
#1143 C1, C2, C5 Server 941 · 82b5b39e Unaffected
#1143 C3, C4 Server 1302 · 50108f6d Unaffected
#1144 C1–C5 Server 941 · 82b5b39e Unaffected
Silo-Server/silo-apple#307 C1–C5; Silo-Server/silo-apple#308 C1–C6 App 01ff70de; server 941 Unaffected
Silo-Server/silo-android#317 C1–C5; Silo-Server/silo-android#318 C1–C6 App c38fb93c; server 941 Unaffected

Validation tasks: changes #1254 C1; changes #1256 C11 remains accurate. Both cases are recorded as Not run. These are affected coverage, with no invalidated pass. I retained the task links despite the automated suggestion to remove them: AGENTS.md requires the line to list affected tasks and cases, and neither link claims a recorded pass. The board helper omitted the closed Person tasks and the installed GitHub CLI could not supply its requested PR field; direct issue reads confirmed the results above. No human validation is claimed.

Coordination: no API or client change is required for Apple, Android or Jellyfin; each reads the same stored people. The manual's audiobook library and listening pages, release definition and feature tables remain accurate. No manual issue is needed. The disclosed batch-insert race and existing duplicate rows remain outside this fix.

Evidence: https://evidence.siloserver.org/r/silo-server/pr-3166-review/

Note

AI disclosure: OpenAI Codex in T3 Code, model gpt-6.1-sol, using GitHub CLI and Go. Codex ran finder, validation, verifier and sweep passes. Claude, model claude-opus-5-5, independently reviewed the source and identified the isolation assumption; Codex reproduced it, fixed it and verified the repair. No merge was performed.

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

Labels

bug Something isn't working evidence-required Needs before-and-after evidence before the Evidence check passes go Pull requests that update go code impact: usability Core flow broken or severely blocked 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.

2 participants