Skip to content

fix(taskmanager): keep task history cleanup from stalling a one-connection pool - #5197

Merged
Quick104 merged 3 commits into
Silo-Server:mainfrom
Rhainland:fix/5111-prune-own-lock-session
Nov 24, 2026
Merged

Quick104 merged 3 commits into
Silo-Server:mainfrom
Rhainland:fix/5111-prune-own-lock-session

Conversation

@Rhainland

@Rhainland Rhainland commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #5111
Related issue: N/A
Validation tasks: none

Other clients: Apple N/A (no client-visible change); Android N/A (no client-visible change); Roku N/A (no client-visible change)

With database.max_connections set to 1, running the task history cleanup (a step of Database Maintenance) stopped the server from answering any request that needed the database. /api/v1/ready reported postgres: false and authenticated API calls timed out until the run's context ended. Only servers that lower the pool to 1 are affected; the default of 20 hides it.

PgExecutionRepository.Prune took its advisory lock with pglock.TryAcquire, which keeps a pooled connection for as long as the lock is held. Its queries then went through the same pool, so with one connection they waited on the connection the lock was holding, and so did everything else on the server.

Approach

The lock now lives on a database session of its own, opened with the pool's configuration but outside the pool, which is how #5110 fixed the cluster task lock. The steps for that are now pglock.TryAcquireSession: open the session, try the lock, and on release unlock first and then close, so another server trying right after finds the lock free. advisoryClusterLock from #5110 now uses the same helper instead of its own copy; its behaviour is unchanged apart from also warning when the unlock reports the lock was not held.

This costs one PostgreSQL connection beyond the pool while a prune runs, the same trade the cluster task lock, storage maintenance, and the notification interest rebuild already make. The prune runs as a step of Database Maintenance, whose own cluster lock already holds one such session, so a maintenance run uses two sessions outside the pool while the prune step runs.

Other pglock.TryAcquire callers are left for follow-ups. Three of them stall a one-connection pool at startup on their own, before any cleanup runs: generate_extra_stills (internal/extrastills/generator.go), release_stored_artwork (internal/metadata/artwork_release.go), and cleanup_chapter_thumbnail_originals (internal/chapterthumbs/originals_cleanup.go). With them scheduled, a server at database.max_connections=1 still stops answering at boot. #5247 tracks them.

Validation

  • Go build, gofmt, go mod tidy -diff, go vet on the changed packages: clean.
  • make lint-changed, make lint-router-recovery: 0 issues.
  • make test-go: passes except internal/notifications TestPushSenderRegistersRelayOnFirstSendWithoutCredential, which fails the same way on origin/main. Five packages that check temp-directory permissions failed under the local umask and pass with umask 022.
  • make test-db-contracts against a migrated Postgres: the new test and the existing task lock tests pass. Backup tests that need S3 or pg_dump were skipped.
  • make verify-local-paths, verify-bidi, verify-case-collisions, verify-size-ratchet: pass.
  • The new database test runs Prune on a one-connection pool and fails on main with listing task history keys: context deadline exceeded. It also checks that Prune still skips while another session holds the lock.

Evidence

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

Checked on a local build with SILO_DB_MAX_CONNECTIONS=1, 500 synthetic task history rows older than the retention window, and the two startup tasks named above unscheduled so the server boots. Same database and steps before and after: run database_maintenance through POST /api/v2/admin/tasks/database_maintenance/run, then probe the server every few seconds.

# main
$ curl /api/v1/ready (before run)                 200 {"status":"ok"}
$ POST /api/v2/admin/tasks/database_maintenance/run 200
$ curl /api/v1/ready (+5s, +10s, +15s)             503 {"status":"error","postgres":false,...}
$ GET /api/v2/admin/tasks/database_maintenance     timed out after 5s (each time)
pg_locks: the task history cleanup lock is held by the pool's only connection, idle

# this branch
$ curl /api/v1/ready (before run)                 200 {"status":"ok"}
$ POST /api/v2/admin/tasks/database_maintenance/run 200
$ curl /api/v1/ready (+5s, +10s, +15s)             200 {"status":"ok"}
$ GET /api/v2/admin/tasks/database_maintenance     200 (2-10 ms), last run completed, cleanup_task_history completed
log: task history cleanup completed deleted=500 retention_days=30 keep_per_task=1000
pg_locks: no task history cleanup or database maintenance lock held after the run; a second run also completes

Risks

A prune now opens one PostgreSQL connection outside the pool for the length of the run, on top of the one Database Maintenance's lock already holds. A deployment whose PostgreSQL connection limit equals the pool size exactly could have the prune fail to connect while the pool is full; the run then fails and the next one retries. The cluster task lock has had the same trade since #5110.

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.

AI Disclosure

  • Harness: Claude Code (via T3 Code); Codex CLI for code review
  • Tool(s): Claude Code, Codex CLI
  • Model(s): claude-opus-5-5; gpt-6.2-sol (code review)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: dual-code-review (gpt-6.2-sol via Codex CLI and claude-opus-5-5, read independently, then reconciled) on the full diff, then again on the follow-up commit. Correctness: one finding from Sol, that the lock session needs a connection beyond the pool and can fail where PostgreSQL's connection limit equals the pool size. It was kept as a stated risk rather than changed, because it is the approach the issue and fix(taskmanager): hold cluster task locks on their own database session #5110 chose. Standards: Opus flagged the new helper as a copy of the fix(taskmanager): hold cluster task locks on their own database session #5110 cluster lock code; fixed by moving the cluster lock onto the helper. Re-review of that commit: no correctness or standards findings; Sol noted the extra "lock was not held" warning, which is accurate and log-only, so it stays.

Note

Fix task history cleanup stalling with a one-connection pool

  • Adds pglock.TryAcquireSession and SessionLock.Release in session.go. Advisory locks are held on a dedicated connection outside the pool, bounded by a releaseTimeout.
  • PgExecutionRepository.Prune in postgres_history.go now holds its cleanup lock on a separate session, so prune queries can use pool connections. Previously the lock occupied a pool connection, and a pool with MaxConns=1 stalled.
  • Refactors advisoryClusterLock.TryAcquire in refresh_all_library_metadata.go to delegate to the new pglock helpers, removing its inline connection lifecycle.
  • Adds a database test verifying Prune succeeds with MaxConns=1 and skips when another session holds the lock.
  • Risk: SessionLock.Release uses a context not canceled with the caller's context; check release/close error joining in session.go if callers relied on cancellation.

Macroscope summarized 82912a1.

Prune took its advisory lock on a pooled connection and then ran its
queries through the same pool. With database.max_connections set to 1,
its first query waited on the connection the lock held, and every other
query on the server waited with it. The lock now lives on a session
outside the pool, as the cluster task lock does since Silo-Server#5110.

pglock.TryAcquireSession is the shared form of that pattern: it opens the
session from the pool's configuration, and Release unlocks before closing
so another server trying right after finds the lock free.
…cquireSession

advisoryClusterLock held its own copy of the session-lock steps the new
helper now owns.
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Nov 23, 2026
@silo-kody

silo-kody Bot commented Nov 23, 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 23, 2026
@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The changes add a shared helper for PostgreSQL advisory locks held on dedicated sessions. Task-history pruning and cluster locking use the helper. A contract test covers pruning with a one-connection pool and lock contention.

Changes: Session-level advisory locks

Layer / File(s) Summary
Dedicated session lock helper
internal/database/pglock/session.go
Adds TryAcquireSession and SessionLock.Release. The helper opens a dedicated connection and uses bounded, cancellation-independent contexts when closing it.
Task-history pruning
internal/taskmanager/repository/postgres_history.go, internal/taskmanager/repository/postgres_history_test.go, scripts/ci/db-contracts.txt
Prune acquires its advisory lock outside the pool. The added contract test checks successful pruning with a one-connection pool and verifies that pruning skips when another session holds the lock.
Cluster lock integration
internal/taskmanager/tasks/refresh_all_library_metadata.go
advisoryClusterLock uses the shared helper for lock acquisition and release. It returns acquisition errors and contention, and logs release errors.

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

Change: Bug fix · Severity of issue fixed: Medium

Possibly related PRs

Suggested reviewers: quick104

Merge Risk: Minimal · up to 2b3e5

Task-history pruning now holds its advisory lock on a separate database session, so cleanup no longer stalls requests when the pool is limited to one connection. Cluster locking uses the same helper, with release errors logged. No merge-blocking risk was found. Pruning needs one connection beyond the pool, so it can fail to connect when the server's connection limit equals the pool size. The run then fails and retries later.

Security architecture risk: Low · up to 2b3e5

The change prevents task-history cleanup from tying up the only connection in a one-connection pool. It preserves coordination between servers, but PostgreSQL needs one more connection slot during cleanup. If no slot is available, the cleanup step can fail rather than run without its lock.

Retained concerns

  • Low · reliability · inferred: Task-history pruning now opens a PostgreSQL connection beyond the configured pool limit while Database Maintenance already holds its own dedicated lock session. If PostgreSQL or the application role has no free slot, pruning fails before deleting anything. Database Maintenance records that step failure and continues with later steps unless canceled; recurring exhaustion can leave history past its retention target.
Security review details

Security Blast Radius

  • inferred — The added capacity demand applies to the PostgreSQL deployment serving task history, not to a new data store or credential. A held key excludes another holder of that key, but contenders open their sessions before learning whether they acquired it.

Trust Boundaries and Controls

  • observed — The standalone lock session does not inherit the application pool's AfterConnect hook. That hook tunes JIT and registers vector types; neither operation is needed by the lock SQL. This separation already applied to cluster locks at the merge base and now also applies to the prune lock session.

Hardening Proposals

  • proposed — Budget PostgreSQL connection headroom for both the maintenance and pruning lock sessions, and monitor cleanup failures caused by connection exhaustion.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: task history cleanup no longer stalls a one-connection pool. The changeset moves the Prune advisory lock onto a session outside the pool (new pglock.TryAcquireSession …
Linked Issues check Passed [#5111] requires that task-history pruning run on a one-connection pool without stalling other database requests. At head, PgExecutionRepository.Prune (internal/taskmanager/repository/postgres_histo…
Out of Scope Changes check Passed Changes at head: (1) new pglock.SessionLock, TryAcquireSession, and Release in internal/database/pglock/session.go, which implement the issue's fix; (2) Prune lock acquisition and comments in …
Description check Passed The description is specific and on-topic. It names the problem (task history cleanup stalling a one-connection pool), the approach (TryAcquireSession on a session outside the pool), the touched code p…
Full details: Title check

Explanation

The title names the main change: task history cleanup no longer stalls a one-connection pool. The changeset moves the Prune advisory lock onto a session outside the pool (new pglock.TryAcquireSession helper), which matches the title's subject and intent. The title is specific, under 80 characters, and uses the conventional fix(taskmanager) prefix.

Full details: Linked Issues check

Explanation

[#5111] requires that task-history pruning run on a one-connection pool without stalling other database requests. At head, PgExecutionRepository.Prune (internal/taskmanager/repository/postgres_history.go) takes its lock with pglock.TryAcquireSession(ctx, r.pool, ...). That helper (internal/database/pglock/session.go) opens a dedicated pgx.Conn from pool.Config().ConnConfig.Copy(), outside the pool. The pool therefore keeps its only connection free, and listTaskKeys, loadDoomedBounds, and deleteTaskHistoryBatch use the pool without waiting on the lock. The skip path is preserved: when another session holds the key, Prune returns Skipped = true. The lock is released by Release, which unlocks before closing, so a following run finds the lock free. The issue's first permitted approach (a session outside the pool, as #5110 does) is implemented. The PR summary reports a new test (TestPgExecutionRepositoryPruneRunsOnASingleConnectionPool) that fails on main with a deadline error and passes with the change. I did not run the test. The unchecked pglock.TryAcquire callers that the issue lists are explicitly deferred by the PR, which the issue permits as a separate scope item.

Full details: Out of Scope Changes check

Explanation

Changes at head: (1) new pglock.SessionLock, TryAcquireSession, and Release in internal/database/pglock/session.go, which implement the issue's fix; (2) Prune lock acquisition and comments in postgres_history.go, which implement the fix; (3) the new database test and its entry in scripts/ci/db-contracts.txt, which cover the fix; (4) advisoryClusterLock in internal/taskmanager/tasks/refresh_all_library_metadata.go now calls the shared helper instead of its own copy of the #5110 logic. Change (4) is a refactor that serves the new helper. Its stated behavior change is limited to a log-only warning when unlock reports the lock was not held, and it does not alter the cluster task lock's acquisition semantics. The PR does not change other pglock.TryAcquire callers, which matches the issue's scope. I found no unrelated change.

Full details: Description check

Explanation

The description is specific and on-topic. It names the problem (task history cleanup stalling a one-connection pool), the approach (TryAcquireSession on a session outside the pool), the touched code paths (PgExecutionRepository.Prune, advisoryClusterLock), validation results, evidence, and risks. It is related to the changeset in detail.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
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: 1b6f168f-1072-4cb2-86ca-aec0783736f7
Commits

Reviewing files that changed from the base of the PR and between 3b2b321 and 2b3e5cf.

Files selected for processing: 5

  • internal/database/pglock/session.go
  • internal/taskmanager/repository/postgres_history.go
  • internal/taskmanager/repository/postgres_history_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 4 included reviews per hour; 3 remain after this review.

@Quick104

Copy link
Copy Markdown
Contributor

/silo review summary

Reviewed head: 82912a1 (the PR commit 2b3e5cf with main merged in; the merge doesn't change the PR's diff).

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

The fix holds up. On a dev sandbox at database.max_connections=1, main stops answering as soon as Database Maintenance starts. The pool's only connection sits idle holding the task history cleanup lock, /api/v1/ready returns 503, and authenticated calls time out. On this head, ready stays 200, admin calls answer in under 10 ms, and the cleanup deletes the seeded rows. A second maintenance run also completes. The new database test fails on main with listing task history keys: context deadline exceeded and passes here.

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

What changed on the branch

Review findings and how they were handled

No defect needs a code change. A council of three models from different providers reviewed this head, alongside a multi-agent code review:

Member Round 1
Sol (gpt-6.2-sol, medium) 8/10
Opus (claude-opus-5-5, medium) 7/10
Gemini (gemini-4-neon, medium) 8.5/10
  • Prune's lock is nested inside the maintenance lock (Opus, Sol, Gemini). Prune runs only as a Database Maintenance step (cmd/silo/main.go), and that task already serializes servers with its own lock. Its own lock now costs a second session outside the pool. I corrected the PR body to say so. Removing Prune's lock would save that session, and it is optional for the maintainers: the lock keeps Prune safe for any future caller, matches fix(taskmanager): hold cluster task locks on their own database session #5110, and costs one connection during a daily run.
  • A failed socket close after a confirmed unlock would report the prune as failed (Sol, Gemini, Opus, code review). pgx ignores errors from sending Terminate and returns only the socket close's error. A plain TCP close doesn't produce one, so the only path is a TLS close-notify write that fails right after a successful unlock round trip. Not changed.
  • sync.OnceFunc no longer wraps the cluster lock's release (Sol, Gemini, code review). A second sequential call is still a no-op, because Release clears its connection. Every caller releases once with defer, so nothing releases concurrently. Not changed.
  • A lock session dropped mid-run loses its lock (Sol). Main behaves the same way, since this is inherent to session-level advisory locks.
  • No unit tests in pglock for the new helper (Gemini). The Prune test and the existing cluster lock test cover both callers against Postgres, so another test would catch nothing new.

Bots: CodeRabbit generated no actionable comments, and Silo Kody left no inline findings.

Pre-existing defects

#5247: generate_extra_stills, release_stored_artwork, and cleanup_chapter_thumbnail_originals each pin a one-connection pool at startup the same way. I reproduced the first two on main. The fix can reuse pglock.TryAcquireSession, so it follows this PR.

Checks

  • Validated features: no passed case on the v1.0 board reaches scheduled-task locking, Database Maintenance, task history, or the full metadata refresh. Validation tasks: none, matching the body.
  • User manual: unaffected. The configuration page describes SILO_DB_MAX_CONNECTIONS without promising anything about connections beyond the pool.
  • Other clients: N/A, a server-side change with nothing a client shows.
  • Also ran: the focused pglock, taskmanager/repository, and taskmanager/tasks tests against a migrated Postgres, and make lint-changed (0 issues). No formal model covers these files.

🤖 Claude Code (claude-opus-5-5)

@Quick104
Quick104 merged commit 92ed2b4 into Silo-Server:main Nov 24, 2026
17 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 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.

[bug] Task history cleanup stalls the server at database.max_connections=1

2 participants