You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(taskmanager): hold cluster task locks on their own database session - #5110
Related issue: N/A (found in review of #4642)
Validation tasks: none
Other clients: N/A (no client-visible change)
About ten scheduled tasks (HDR10+ and Matroska backfills, marker detection, database maintenance, the full metadata refresh, and others) take a cluster-wide advisory lock so only one server runs them. The lock held one of the pool's connections for the whole run, and the task then ran its own queries through that same pool. database.max_connections (or SILO_DB_MAX_CONNECTIONS) accepts values down to 1. At 1, the task's first query waited for the connection its own lock was holding, and every other database request on that server waited behind it until the task was cancelled. The default of 20 doesn't hit this. It takes a low configured value and a task that holds the lock, such as the startup HDR10+ backfill.
This change keeps the lock on a database session of its own, outside the pool. Closing that session releases the lock.
Approach
advisoryClusterLock.TryAcquire now opens a session from the pool's connection config, takes pg_try_advisory_lock there, and closes the session on release. Storage maintenance already does the same in downloads.ArtifactRepository.WithMaintenanceLock. Every task that uses this lock gets the fix, and no caller changes.
I didn't raise the setting's floor, for two reasons. The server already supports a pool of 1 on purpose: the chapter thumbnail lock, the local sidecar locks, and storage maintenance each open a separate session for small pools. And no floor fixes this kind of stall. Each lock-holding task pins one connection, so a pool of N still stalls once N such tasks run at the same time. A session outside the pool removes the dependency for any pool size.
I left pglock.TryAcquire as it is because some of its callers do all their work on the locked connection (lock.Conn(), for example the blob GC sweep), and those are correct. Other pglock.TryAcquire callers that query the pool while holding the lock have the same stall at a pool size of 1. Task history cleanup is one, confirmed by trace. They are outside this PR.
Validation
A new Postgres test opens a one-connection pool, takes a cluster task lock, and runs a pool query. On the unfixed base it fails with context deadline exceeded. With the fix it passes. It is listed in scripts/ci/db-contracts.txt.
go test ./internal/taskmanager/tasks/, go vet: pass. make lint-changed: 0 issues.
Surface and build: no visible change. The evidence page has the steps, the build, and both test runs.
Risks
On each server, a running lock-holding task now uses one Postgres connection outside database.max_connections instead of one inside it. These tasks are few per server, and the pool no longer gives up a connection to them, so the total stays about the same.
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.
Council review
This ran as a follow-up run. The plan round was skipped under the small-fix rule: one file, about 30 production lines, no contract or migration. The background review used one member, Sol (gpt-6.2-sol), at medium effort.
Round 1, on 885097a, scored 7/10. Two findings are fixed in c4379b1: release now unlocks before closing the session, and opening the session is bounded to 5 s. The third finding, that lock sessions count outside the pool, is answered in its thread.
Round 2, on c4379b1, scored 9/10. Its one low finding, a second release logging an error, is fixed in b518e01.
Left for the user: nothing.
Follow-up: #5111 tracks the same stall in task history cleanup, plus unchecked candidates among the other pglock.TryAcquire callers.
AI Disclosure
Harness: Claude Code in T3 Code
Tool(s): Claude Code
Model(s): claude-opus-5-5
Involvement: Fully AI-generated, human verified
Adversarial review: two background rounds by Sol at medium effort; see Council review.
Hold cluster advisory locks on a dedicated database session
tasks.advisoryClusterLock.TryAcquire now opens its own database session from the pool's connection config and takes a session-level PostgreSQL advisory lock there, instead of using a pglock connection from the task's query pool. A held lock no longer occupies a pool connection.
Release attempts to unlock and close the session using contexts detached from caller cancellation; session closure also releases the lock. Lock-session operations are bounded by the new clusterLockSessionTimeout (5 seconds).
Adds an integration test that verifies queries still work through a one-connection pool while the lock is held, and that the lock can be reacquired after release; registers it in db-contracts.txt.
Behavioral Change: TryAcquire returns no lock when the pool is nil, and release logs a warning instead of failing on unlock errors.
A cluster task's advisory lock pinned one of the pool's connections for the
whole run while the task queried through the same pool. With
database.max_connections set to 1, the task's first query waited on its own
connection and every other query on the node stalled with it. The lock now
lives on a session outside the pool, and closing that session releases it.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 settingsReview Options
The following review options are enabled or disabled:
Options
Enabled
Bug
✅
Performance
✅
Security
✅
Business Logic
❌
silo-triageBot
added
bug
Something isn't working
go
Pull requests that update go code
impact: usability
Core flow broken or severely blocked
priority: P2
Limited scope, workaround exists, or polish
triaged
High-confidence review completed; does not mean fixed, validated, or accepted for release.
labels
Nov 22, 2026
The cluster lock now uses a dedicated PostgreSQL session to acquire and release advisory locks. A PostgreSQL integration test checks that a query can run while the lock is held in a single-connection pool and that lock acquisition resumes after release.
Changes: PostgreSQL cluster lock
Layer / File(s)
Summary
Dedicated-session lock acquisition and release internal/taskmanager/tasks/refresh_all_library_metadata.go
TryAcquire opens a dedicated PostgreSQL session and attempts the advisory lock. It closes the session on errors, contention, and release. Release uses a five-second timeout and logs close failures.
Single-connection pool contract test internal/taskmanager/tasks/cluster_lock_postgres_test.go, scripts/ci/db-contracts.txt
The PostgreSQL integration test checks that a pool query completes while the lock is held and that acquisition succeeds again after release. The database contract list includes the test.
The change fixes the one-connection pool stall by holding cluster locks on their own session. The new database contract test could fail intermittently if the lock is reacquired before the server drops the old session. Retrying acquisition within a deadline would make it stable.
Security architecture risk: Minimal · up to 88509
The change removes a database-pool starvation failure while preserving exclusive task execution and cancellation-independent cleanup. No introduced security or material failure-containment defect was established.
Retained concerns
No architecture-level concerns identified.
Security review details
Security Blast Radius
inferred — The changed resource boundary is PostgreSQL connection capacity and cluster-wide task coordination within the configured database. It does not establish a new tenant-facing entrypoint or privilege grant; the new lock session inherits the existing connection configuration.
Trust Boundaries and Controls
observed — The dedicated connection uses the pool’s ConnConfig but bypasses its AfterConnect hook. Inspection resolves the potential control-bypass question: that hook configures JIT and registers vector codecs, rather than establishing an authorization role or tenant isolation policy.
Resilience and Maintainability Implications
observed — Existing task reservations atomically reject another start while the same worker is running or cancelling. Both manual and scheduled paths use that reservation mechanism. This limits repeated-start amplification for one worker, although it is not a global connection budget across distinct tasks or servers.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the main change: cluster task advisory locks now run on their own database session instead of a pool connection. It uses the conventional fix(scope) form, is one sentence, and matches …
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
The description states the problem, the cause, the approach, validation, and risks. It matches the changeset: advisoryClusterLock.TryAcquire now uses a dedicated session for the advisory lock, and the…
Full details: Title check
Explanation
The title names the main change: cluster task advisory locks now run on their own database session instead of a pool connection. It uses the conventional fix(scope) form, is one sentence, and matches the changeset, which moves advisoryClusterLock.TryAcquire to a dedicated session.
Full details: Description check
Explanation
The description states the problem, the cause, the approach, validation, and risks. It matches the changeset: advisoryClusterLock.TryAcquire now uses a dedicated session for the advisory lock, and the new Postgres test and db-contracts.txt entry are described. The description is specific and not off-topic.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Full SHA 885097a838fbd7554ff2cb49ef4a403eeeab5be4. The regression test passed 30 runs against local PostgreSQL 18. Delaying the PostgreSQL Terminate message reproduced the immediate reacquisition failure.
The reason will be displayed to describe this comment to others. Learn more.
[R3] Medium. Account for lock sessions in the PostgreSQL connection budget. When ordinary PostgreSQL slots are occupied by idle application pool connections, the old code could borrow one for the lock and use another for the task. The new connection instead gets SQLSTATE 53300 and the task fails before attempting the lock. A fresh session is also required on every contender before it can discover that the lock is held. The Postgres tuner reserves a flat 20 slots above one application pool (internal/database/postgres_tune.go:507), which does not size this across nodes. Document the required headroom across API nodes and bound concurrent lock connections, or give them an explicit connection budget.
The reason will be displayed to describe this comment to others. Learn more.
Not changing this one. The PR's Risks section covers it. At most one session per lock key per server is open while a task runs, and the pool no longer gives up a connection to these tasks. The connection total stays about the same. Storage maintenance (WithMaintenanceLock) and the chapter thumbnail and local sidecar locks already open sessions outside the pool, so the PostgreSQL connection budget already has to allow for them. A database with no free slot fails the run with a connection error and does not stall it, and the next trigger retries.
…sion
Closing the socket returns before PostgreSQL ends the backend, so another
server trying the lock right after could still find it held. Release now
unlocks first and then closes. Opening the session is bounded to five
seconds, like the chapter thumbnail lock session.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Functional Correctness · Quick win
Wait for server-side lock release before failing reacquisition.
If the first backend delays processing Terminate, the new backend can still observe its lock. In pgx v5.9.2, Close closes the client socket without waiting for backend termination. Session advisory locks remain held until the session ends. This makes Line 50 timing-dependent and can fail the registered CI contract despite correct eventual release. (raw.githubusercontent.com)
Retry acquisition within a bounded deadline. Release the successful acquisition, and fail only if the deadline expires or acquisition returns an error.
…ction pool (#5197)
Task history cleanup now holds its advisory lock on a database session of its own, outside the pool, so its queries and the rest of the server still get a connection when database.max_connections is 1. The open-lock-release steps move into pglock.TryAcquireSession, and the cluster task lock from #5110 now uses the same helper.
* fix(taskmanager): hold the task history cleanup lock on its own session
* refactor(taskmanager): take the cluster task lock through pglock.TryAcquireSession
Closes#5111
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bugSomething isn't workinggoPull requests that update go codeimpact: usabilityCore flow broken or severely blockedpriority: P2Limited scope, workaround exists, or polishsize/M50–199 added + deleted lines (all files); change volume, not priority.triagedHigh-confidence review completed; does not mean fixed, validated, or accepted for release.
1 participant
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Related issue: N/A (found in review of #4642)
Validation tasks: none
Other clients: N/A (no client-visible change)
About ten scheduled tasks (HDR10+ and Matroska backfills, marker detection, database maintenance, the full metadata refresh, and others) take a cluster-wide advisory lock so only one server runs them. The lock held one of the pool's connections for the whole run, and the task then ran its own queries through that same pool.
database.max_connections(orSILO_DB_MAX_CONNECTIONS) accepts values down to 1. At 1, the task's first query waited for the connection its own lock was holding, and every other database request on that server waited behind it until the task was cancelled. The default of 20 doesn't hit this. It takes a low configured value and a task that holds the lock, such as the startup HDR10+ backfill.This change keeps the lock on a database session of its own, outside the pool. Closing that session releases the lock.
Approach
advisoryClusterLock.TryAcquirenow opens a session from the pool's connection config, takespg_try_advisory_lockthere, and closes the session on release. Storage maintenance already does the same indownloads.ArtifactRepository.WithMaintenanceLock. Every task that uses this lock gets the fix, and no caller changes.I didn't raise the setting's floor, for two reasons. The server already supports a pool of 1 on purpose: the chapter thumbnail lock, the local sidecar locks, and storage maintenance each open a separate session for small pools. And no floor fixes this kind of stall. Each lock-holding task pins one connection, so a pool of N still stalls once N such tasks run at the same time. A session outside the pool removes the dependency for any pool size.
I left
pglock.TryAcquireas it is because some of its callers do all their work on the locked connection (lock.Conn(), for example the blob GC sweep), and those are correct. Otherpglock.TryAcquirecallers that query the pool while holding the lock have the same stall at a pool size of 1. Task history cleanup is one, confirmed by trace. They are outside this PR.Validation
context deadline exceeded. With the fix it passes. It is listed inscripts/ci/db-contracts.txt.go test ./internal/taskmanager/tasks/,go vet: pass.make lint-changed: 0 issues.Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/cluster-task-lock-own-session/
Surface and build: no visible change. The evidence page has the steps, the build, and both test runs.
Risks
On each server, a running lock-holding task now uses one Postgres connection outside
database.max_connectionsinstead of one inside it. These tasks are few per server, and the pool no longer gives up a connection to them, so the total stays about the same.Checklist
Council review
This ran as a follow-up run. The plan round was skipped under the small-fix rule: one file, about 30 production lines, no contract or migration. The background review used one member, Sol (gpt-6.2-sol), at medium effort.
Follow-up: #5111 tracks the same stall in task history cleanup, plus unchecked candidates among the other
pglock.TryAcquirecallers.AI Disclosure
🤖 Generated with Claude Code
Note
Hold cluster advisory locks on a dedicated database session
tasks.advisoryClusterLock.TryAcquirenow opens its own database session from the pool's connection config and takes a session-level PostgreSQL advisory lock there, instead of using a pglock connection from the task's query pool. A held lock no longer occupies a pool connection.clusterLockSessionTimeout(5 seconds).TryAcquirereturns no lock when the pool is nil, and release logs a warning instead of failing on unlock errors.Macroscope summarized b518e01.