Skip to content

fix(database): keep startup locks outside the pool - #5256

Open
7487 wants to merge 2 commits into
Silo-Server:mainfrom
7487:fix/issue-5247-bug-three-startup-tasks-stall-the-server
Open

7487 wants to merge 2 commits into
Silo-Server:mainfrom
7487:fix/issue-5247-bug-three-startup-tasks-stall-the-server

Conversation

@7487

@7487 7487 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #5247
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)

When database.max_connections is 1, three startup maintenance jobs reserve the pool's only connection for an advisory lock and then wait forever for another connection from that pool. This change keeps those locks on dedicated sessions so the jobs can continue using the configured pool.

Approach

Use the existing session-lock helper for extra-still generation, stored-artwork release, and original-thumbnail cleanup. The helper opens the advisory lock outside the configured pool and closes that session when the job releases the lock. Database contract tests run each path with a one-connection pool and verify that its catalog or callback query can still complete.

The change is internal to the server. It does not alter APIs, schemas, configuration, or client behavior.

Validation

  • TDD reproduction: all three new database cases failed before the production change with context deadline exceeded at MaxConns=1.
  • Focused database tests: all three regression cases passed after the change, including a race-enabled run.
  • Database contract suite: all 1,093 pins passed.
  • Go checks: embed stub, build, formatting, module tidy diff, vet, changed-code lint, router-recovery lint, and the full Go test target passed.
  • Web checks after rebasing onto current main: install, lint, formatting, typecheck, build, bundle budget, and 3,357 tests in 340 files passed.
  • Generated and repository checks: settings bindings, playback fixtures, route inventory, API v2 OpenAPI/types/contracts/fixtures, router artifact, local-path leaks, case collisions, workflow lint, shell lint, size ratchet, bidi scan, migrations, and Prometheus rules passed.

Evidence

There is no user-visible surface. Before the production change, each new one-connection-pool regression case reached its two-second deadline with context deadline exceeded. At commit 501d373caa9037cab71915e4dc0dac72e73c519d, the same focused cases and the full contract suite completed:

ok  github.com/silo-server/silo-server/internal/extrastills
ok  github.com/silo-server/silo-server/internal/metadata
ok  github.com/silo-server/silo-server/internal/chapterthumbs
dbpins: all 1093 pins passed

Test Files  340 passed (340)
Tests       3357 passed (3357)
bundle check: passed

The server and web production builds also completed at that commit.

Risks

An acquired job temporarily uses one dedicated database connection in addition to the configured pool. The connection is closed with the advisory-lock release, including deferred releases on error paths.

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: OpenAI Codex desktop agent
  • Tool(s): Codex
  • Model(s): GPT-5 (reported by the Codex session)
  • Involvement: Fully AI-generated; human review pending
  • Adversarial review: Codex reviewed the complete diff, all three callers, lock-release paths, one-connection boundary behavior, and test registration. CodeRabbit found that the extra-still test could pass without proving its catalog query ran; commit 501d373 added a query tracer, and the focused race test, full Go suite, lint, and all 1,093 database pins passed afterward. No findings remain.

Note

Acquire advisory startup locks via TryAcquireSession instead of TryAcquire

  • Switches advisory-lock acquisition in OriginalsCleaner.Exclusive, extrastills.Generator.Generate, and NewStoredArtworkReleaser from TryAcquire to TryAcquireSession, keeping the lock tied to a session rather than a pooled connection
  • Adds database regression tests for each path that use a one-connection pool and query the database while the lock is held; tests skip when SILO_TEST_DATABASE_URL is unset
  • Adds a configurable test-pool helper storedArtworkReleaseTestPoolWithMaxConns and a query tracer that records FROM media_extras queries
  • Registers the three new one-connection-pool tests in db-contracts.txt
  • Behavioral Change: locked callbacks can now use the pool while the lock is held, so work no longer deadlocks in pools with a single connection

Macroscope summarized 501d373.

@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Nov 24, 2026
@silo-kody

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

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Three startup maintenance tasks now acquire advisory locks with pglock.TryAcquireSession. Database-backed tests check that each task can query through a pool limited to one connection.

Changes: Startup Maintenance Locks

Layer / File(s) Summary
Session-based lock acquisition
internal/chapterthumbs/originals_cleanup.go, internal/extrastills/generator.go, internal/metadata/artwork_release.go
The three maintenance tasks now use pglock.TryAcquireSession to acquire advisory locks.
One-connection pool validation
internal/chapterthumbs/originals_cleanup_db_test.go, internal/extrastills/generator_db_test.go, internal/metadata/artwork_release_db_test.go, scripts/ci/db-contracts.txt
Database-backed tests check that each task can query through a pool limited to one connection. The contract manifest includes the three tests.

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

Change: Bug fix · Severity of issue fixed: Medium

Possibly related issues

Possibly related PRs

Suggested reviewers: quick104, rhainland

Merge Risk: Minimal · up to 501d3

Startup maintenance jobs now hold their advisory locks on dedicated sessions, so they no longer stall when the pool is limited to one connection. Regression tests cover all three jobs, and no merge-blocking risk remains.

Security architecture risk: Minimal · up to 501d3

The change fixes a startup stall without changing who can run maintenance or what those jobs can access. It does require database connection headroom outside the application pool while the jobs hold their locks.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The change is scoped to three existing maintenance paths and their shared database. Overlapping attempts across jobs or replicas can increase demand against the database's own connection limit, but do not grant new privileges.

Trust Boundaries and Controls

  • observed — The direct connection skips the pool's setup hook, which tunes JIT and registers vector types. The dedicated session runs parameterized advisory-lock operations; the guarded maintenance queries still use the pool.

Resilience and Maintainability Implications

  • observed — Each successful acquisition has a single deferred release. Unlock and close use bounded contexts independent of caller cancellation; sequential repeated release is a no-op. If unlock cannot be confirmed, the session is closed rather than returned for reuse. After an interruption, lock ownership lasts until PostgreSQL ends that session.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "fix(database): keep startup locks outside the pool" matches the main change. The PR switches three startup maintenance jobs (extra-still generation, stored-artwork release, original-thumbna…
Linked Issues check Passed Directly linked issue #5247 asks that generate_extra_stills, release_stored_artwork, and cleanup_chapter_thumbnail_originals run with database.max_connections=1. The issue accepts holding the advisory…
Out of Scope Changes check Passed All changed files relate to the objective of #5247. The three production files change only the lock-acquisition call to pglock.TryAcquireSession. The test files add one-connection-pool regression test…
Description check Passed The description is specific and related to the changeset. It states that the three startup maintenance jobs (extra-still generation, stored-artwork release, and original-thumbnail cleanup) reserved th…
Full details: Title check

Explanation

The title "fix(database): keep startup locks outside the pool" matches the main change. The PR switches three startup maintenance jobs (extra-still generation, stored-artwork release, original-thumbnail cleanup) from pglock.TryAcquire to pglock.TryAcquireSession, so their advisory locks sit on dedicated sessions outside the configured pool. This keeps the jobs from stalling when database.max_connections is 1.

Full details: Linked Issues check

Explanation

Directly linked issue #5247 asks that generate_extra_stills, release_stored_artwork, and cleanup_chapter_thumbnail_originals run with database.max_connections=1. The issue accepts holding the advisory lock with pglock.TryAcquireSession. At head 501d373, Generator.Generate in internal/extrastills/generator.go calls pglock.TryAcquireSession(ctx, g.pool, lockKey) (SILOEXT). The error and not-acquired handling and the deferred release are unchanged. The raw summary reports the same one-line change in NewStoredArtworkReleaser (internal/metadata/artwork_release.go) and OriginalsCleaner.Exclusive (internal/chapterthumbs/originals_cleanup.go). The incremental change since 1d616af (commit 501d373, 'test(extrastills): require the catalog query') strengthens generator_db_test.go. It adds a trace that requires a FROM media_extras query to run before the test passes. Automated coverage for all three paths uses a one-connection pool and checks that a pool query completes while the lock is held. The three tests are registered in scripts/ci/db-contracts.txt. Limits: the incremental diff could not be read because changed blobs were unavailable. I did not inspect the pglock helper source or the artwork_release and originals_cleanup files at head directly. Their behavior rests on the change summary and the PR's reported test runs.

Full details: Out of Scope Changes check

Explanation

All changed files relate to the objective of #5247. The three production files change only the lock-acquisition call to pglock.TryAcquireSession. The test files add one-connection-pool regression tests for those three paths. The artwork_release_db_test.go change adds a max-connection parameter to the existing test pool helper and keeps the four-connection default. The scripts/ci/db-contracts.txt entries register the new tests. The incremental change since 1d616af adds a query assertion to the extrastills regression test only, which supports the objective. No unrelated behavior, API, schema, configuration, or client change appears in the summary. Limit: the incremental text diff was unavailable, so this relies on the commit subject and the change summary.

Full details: Description check

Explanation

The description is specific and related to the changeset. It states that the three startup maintenance jobs (extra-still generation, stored-artwork release, and original-thumbnail cleanup) reserved the only pool connection for an advisory lock when database.max_connections is 1. It explains that the change switches these locks to dedicated sessions via the session-lock helper, and it describes the new one-connection-pool regression tests, the db-contracts manifest registration, the added test helper and query tracer, and the risk of one extra temporary connection. This matches the changed files in the raw summary.

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: 35597223-8326-4484-b516-6df7a698a936
Commits

Reviewing files that changed from the base of the PR and between 1d616af and 501d373.

Files selected for processing: 1

  • internal/extrastills/generator_db_test.go

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

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

Nitpick comments: 1

internal/extrastills/generator_db_test.go: 1

33-35: Trivial · Maintainability & Code Quality · Quick win

Confirm that Generate executes the catalog query.

If another session holds lockKey, Generate returns (0,0,nil) without querying the pool. This assertion then passes with either lock implementation.

Add an observation of catalog-query execution, for example with a pgx.QueryTracer, and require that observation before accepting success. Keep limit=0 to avoid extraction dependencies.

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: 0c19d22a-727e-4141-8393-adf5fac69024
Commits

Reviewing files that changed from the base of the PR and between 1fffd31 and 1d616af.

Files selected for processing: 7

  • internal/chapterthumbs/originals_cleanup.go
  • internal/chapterthumbs/originals_cleanup_db_test.go
  • internal/extrastills/generator.go
  • internal/extrastills/generator_db_test.go
  • internal/metadata/artwork_release.go
  • internal/metadata/artwork_release_db_test.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.

@silo-kody

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

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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] Three startup tasks stall the server at database.max_connections=1

1 participant