Skip to content

Postgres: midnight scans freeze every admission slot (request-media locks, idle in transaction) #729

Done

Description

@n1coh

On Postgres (v3.72.35, commit c5ca5cc), SeerrNG freezes almost every night at midnight, when the scheduled scans start together. None of them finishes. Download Sync then logs Scheduled job is already running every minute, and only a restart helps. This is a different path from #681, which is fixed in this version.

Setup

  • PostgreSQL 18, DB_POOL_SIZE=8, so min(8, pool - 1) = 7 admission slots.
  • One Radarr, one Sonarr, Jellyfin as the media server.
  • It also happened with other pool sizes, so other slot counts.

What happens

At midnight (local time), these jobs start within 60 ms of each other: Download Recovery, Jellyfin Recently Added Scan, Sonarr Scan, Radarr Scan.

  • Jellyfin Sync logs Beginning to process recently added for its two libraries (00:00:00 and 00:00:04), then nothing.
  • Sonarr Scan and Radarr Scan log Beginning to process … server, then nothing.
  • From 00:02, Download Sync (every minute) logs Scheduled job is already running. Jellyfin Recently Added Scan logs the same at its next runs (00:05, 00:10).
  • On SIGTERM, the drain ends with timedOutTasks: ["scheduled jobs and background tasks"].

Evidence

We sampled pg_stat_activity and pg_locks on the seerr database every minute from 00:01 to 00:10. All ten samples were identical:

  • 7 sessions were idle in transaction, with wait event Client:ClientRead. Their transactions started at 00:00:02. The last statement of each was SELECT pg_advisory_xact_lock(hashtextextended($1, 0)).
  • Each of the 7 sessions held exactly one advisory ExclusiveLock, granted. pg_blocking_pids() was empty for all of them, and no session was waiting on a lock.
  • We matched the lock keys against hashtextextended(key, 0) over the media table. They are 7 distinct request-media keys: request-media:movie:<tmdbId> for 6 movies and request-media:tv:<tmdbId> for 1 show.
  • Another connection kept running the scheduled_job_lease queries every minute, so the database itself stayed responsive.

Reading

All 7 slots of RequestAdmissionCoordinator were held by scan admissions on request-media keys. None of them sent another statement after taking its advisory lock: no media-row:* lock was taken, and no query ran. PostgreSQL was not waiting on anything, so the wait was inside the process. That leaves the local AsyncLocks taken after the advisory lock, or a nested requestAdmission.run() that left the AsyncLocalStorage context and was dispatched to another slot. Once all slots are held like this, nothing can make progress. We could not tell which of these happens from outside the process.

The scan paths that take request-media keys at that moment are runWithRequestAdmission(...) in baseScanner (followed by this.asyncLock.dispatch(tmdbId, …)), the Radarr and Sonarr scanners' batch admissions, and runMediaEntityMutation.

Workaround

A liveness probe restarts the container once a transaction has been idle in transaction for more than 10 minutes. idle_in_transaction_session_timeout alone does not unfreeze the app, as in #681.

Possible fixes

The release notes of v3.72.36 to v3.72.40 do not seem to cover this, and we have not tried those versions yet. We can run another capture if you need one, for example with debug logging of slot dispatches.

Activity

  1. github-actions commented on Nov 26, 2026

    @github-actions

    Possible duplicate detected

    This issue may be a duplicate of the following (detected via semantic similarity + LLM review):

    A maintainer will review this. If this is not a duplicate, no action is needed.

  2. frejagail commented on Nov 26, 2026

    @frejagail

    I hit the same nightly freeze on v3.72.40 (Postgres) and traced it to a lock-order inversion between service admission and the scanners.

    Cause

    • runWithServarrAdmissionResources (lib/serviceAdmission) takes the in-memory serviceAdmissionLock on service-config:<type>:<id> first, and only then calls requestAdmission.run(), which waits for an admission slot.
    • Scanner items do the reverse: they hold a slot (their request-media admission) and then take the same in-memory lock through mutationGuard -> runWithServarrServiceSnapshot.
    • The Sonarr scan processes 50 series at once (bundleSize: 50) and uses both orders: some series call runWithServarrServiceSnapshot(... getEpisodes ...) outside any admission (lock held, waiting for a slot), while others are inside processShow (slot held, waiting for the lock). Once every slot is held by an item waiting for the lock, nothing moves. So the Sonarr scan can deadlock on its own, without another job running.
    • Download Sync (downloadtracker.runWithCurrentServarrDownloadServer -> runWithServarrServiceAdmission) takes the same lock outside an admission context, so it collides with any scan in the same way. That is the job that starts logging "already running" first. Download Recovery then queues behind the held slots, but as far as I can tell it doesn't take this lock itself.

    This matches what you captured: every slot is idle in transaction right after pg_advisory_xact_lock on a request-media key, no session is blocked in PostgreSQL, and the wait is inside the process.

    Fix

    Take the admission first and the in-memory lock inside it. This is the order the configuration, media, user-security and override-rule admission helpers already use. authAccountAdmission has the same inverted order, so I changed it too. In the compiled dist/lib/serviceAdmission.js:

         const dispatch = (index) => index === orderedResources.length
    -        ? requestAdmission_1.default.run(orderedResources, callback)
    +        ? callback()
             : serviceAdmissionLock.dispatch(orderedResources[index], () => dispatch(index + 1));
    -    return dispatch(0);
    +    return requestAdmission_1.default.run(orderedResources, () => dispatch(0));

    The change to dist/lib/authAccountAdmission.js has the same shape (keys / authAccountAdmissionLock). Nested admissions don't take a slot, so a holder of the in-memory lock never waits for a slot after this change.

    I applied it as a build-time patch. My build also queues on the exact key set with a shared permit count instead of hashed slots, which is a separate local change, but the inversion is the same with hashed slots. After the change, the Sonarr, Lidarr and Bookshelf scans fired together from cron while Download Sync was running. All three finished (26 to 70 s), and no job was left running.

    Side note on testing

    "Run now" (POST /api/v1/settings/jobs/:id/run) calls job.invoke() inside the route's authorizedMutation admission context. The scan inherits that AsyncLocalStorage context after the route has released its query runner, so it stops immediately with Query runner already released. Cannot run queries anymore. (stack: acquireLocks <- run existingContext branch <- runWithServarrServiceSnapshot <- SonarrScanner.run). Scans therefore have to be tested from a cron trigger. Running invoked jobs outside the request context (for example AsyncLocalStorage.exit / a fresh async root) would fix that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions