Skip to content

fix(taskmanager): hold cluster task locks on their own database session - #5110

Merged
Quick104 merged 3 commits into
mainfrom
fix/cluster-task-lock-own-session
Nov 22, 2026
Merged

Quick104 merged 3 commits into
mainfrom
fix/cluster-task-lock-own-session

Conversation

@Quick104

@Quick104 Quick104 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

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

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

🤖 Generated with Claude Code

Note

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.

Macroscope summarized b518e01.

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]>
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Nov 22, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-22T06:48:14.680696Z c4379b1 New commits
🔒 Security Review ✅ Completed 2026-11-22T06:54:41.116631Z b518e01 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@silo-kody

silo-kody Bot commented Nov 22, 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 ❌

@silo-triage silo-triage Bot 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
@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

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.

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

Change: Bug fix

Suggested reviewers: rhainland

Merge Risk: Low · up to 88509

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: Passed 4

Check name Status Explanation
Title check Passed 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 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 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

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adversarial review (gpt-6.2-sol, reviewed 885097a)

Full SHA 885097a838fbd7554ff2cb49ef4a403eeeab5be4. The regression test passed 30 runs against local PostgreSQL 18. Delaying the PostgreSQL Terminate message reproduced the immediate reacquisition failure.

return nil, false, nil
}
session, err := pgx.ConnectConfig(ctx, l.pool.Config().ConnConfig)
if err != nil {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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]>
@silo-kody

silo-kody Bot commented Nov 22, 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 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.

Actionable comments posted: 1

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: de578d06-0c1a-47b4-abca-6a1b9b2b0c14
Commits

Reviewing files that changed from the base of the PR and between 1d6a023 and 885097a.

Files selected for processing: 3

  • internal/taskmanager/tasks/cluster_lock_postgres_test.go
  • internal/taskmanager/tasks/refresh_all_library_metadata.go
  • scripts/ci/db-contracts.txt

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

t.Fatalf("second TryAcquire while held = %v, %v; want skipped", acquired, err)
}
release()
again, acquired, err := lock.TryAcquire(t.Context())

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.

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.

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adversarial review (gpt-6.2-sol, reviewed c4379b1)

One low severity finding about repeated release. The focused task tests passed against PostgreSQL 18.

@silo-kody

silo-kody Bot commented Nov 22, 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 merged commit e7a8d80 into main Nov 22, 2026
16 of 19 checks passed
@Quick104
Quick104 deleted the fix/cluster-task-lock-own-session branch November 22, 2026 17:08
Quick104 pushed a commit that referenced this pull request Nov 24, 2026
…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
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 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. 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.

1 participant