Webhook-driven automation for Sonarr/Radarr + Deluge, deployed as a Docker container on Unraid.
arr-webhook.py runs a Flask app (port 9876) that Sonarr and Radarr call via their notification webhooks:
- On Grab: if the grab is a quality upgrade and the release is over 10GB, labels the new torrent in Deluge so it can be throttled/tracked separately instead of competing with normal downloads. Once it is in that lane the queue dupe pass runs immediately, scoped to just that movie/series, so a second in-flight release of the same thing is resolved in seconds rather than waiting for the daily sweep.
- On Download (import) of an upgrade: finds the old torrent that the new file replaced and either deletes it immediately (PROPER/REPACK) or labels it
supersededand moves it to a seeding directory.
Background schedulers (run inside the same process):
- Daily: removes
supersededtorrents that have seeded pastSEED_DAYS(default 21), and dedupes Radarr's and Sonarr's downloads (this and the weekly run are the unscoped backstop behind the grab-time pass, covering missed webhooks and grabs that happened while the service was down) (Radarr: highest custom-format-score entry per movie; Sonarr: best covering release per overlapping episode set — both across the *arr's own queue and the throttledradarr-upgrade/sonarr-upgradelane, which that queue cannot see). - Hourly: trims the upgrade lane to
UPGRADE_LANE_MAX(see Deluge trimming), then bumps normalsonarr/radarr-labeled torrents to the top of the Deluge queue. - Daily: retires long-seeded torrents (see Deluge trimming).
- Monthly (1st of month): purges stalled upgrade torrents, triggers a Radarr bulk search to catch missed upgrades, waits, then relabels/requeues anything that came in as a result.
monthly_upgrade.py is a standalone script duplicating the monthly cycle (purge → bulk search → wait 90 min → relabel/requeue), kept for manual or cron-triggered runs independent of the long-running webhook process.
media_share.py adds a friend-facing media upload portal (Flask blueprint, registered into the same app/port) at /share:
- Friends authenticate via Cloudflare Access. The app takes the identity from the email in the validated
Cf-Access-Jwt-AssertionJWT (see Access control); the plain email header is ignored, so a spoofed header gets nothing./share/admin*needs theADMIN_EMAILidentity, and/share/status/<id>shows an upload only to its owner (or the admin). - Browse the read-only-mounted Movies/TV Shows/Music libraries and upload a file or whole folder to that friend's own SFTP server, looked up by their authenticated email in
FRIENDS_CONFIG. - Uploads run in a background thread, throttled to
UPLOAD_RATE_LIMIT_MBIT(default 5 Mbit/s) so a large upload doesn't saturate the connection. - Every upload is logged to a SQLite DB (
/data/share_uploads.db);/share/usageshows each friend their own bandwidth usage over the last 7/30/60/90/182/365 days.
- Copy
.env.exampleto.envand fill in:DELUGE_PASSWORDSONARR_API_KEYRADARR_API_KEYFRIENDS_CONFIG(JSON map of Cloudflare Access email → SFTP destination) if using the media share portal
- Adjust the hardcoded Deluge/Sonarr/Radarr URLs, labels,
SEED_DAYS,SEEDING_DIR, and the/mnt/Media/...library volume mounts directly indocker-compose.ymlif your setup differs. - Build and run:
docker-compose build && docker-compose up -d - Point Sonarr/Radarr's webhook connections (Settings → Connect) at
http://<container-ip>:9876/webhook/sonarrand/webhook/radarr, enabling the On Grab and On Import (upgrade) triggers. - If using the media share portal, point a Cloudflare Tunnel + Access application at
http://<container-ip>:9876/shareand restrict ingress so the container is only reachable through the tunnel.
One before_request gate (app_auth.py) covers every route, including /share.
| Variable | Meaning |
|---|---|
APP_AUTH_MODE |
off, log (default) or enforce. Anything else is treated as enforce. |
CF_ACCESS_TEAM_DOMAIN |
The Access team domain. Signing keys come from https://<domain>/cdn-cgi/access/certs (cached 1 h, refetched on an unknown key id). |
CF_ACCESS_AUDS |
Comma-separated AUD tags of the Access applications that may reach this app. |
APP_AUTH_TOKEN_FILE |
File of bearer tokens, one per line (# comments). A line is the plain token or sha256:<hex> of it (the sha-256 of the token, hex), so a caller such as the Mac can keep its token in its Keychain and only the hash is stored here. Compared in constant time. For scripts and the glacier mover. |
APP_AUTH_BASIC_FILE |
File of user:password lines. Accepted on /webhook/* only, for Sonarr/Radarr. |
APP_AUTH_LAN_OPEN |
Exact paths a LAN caller may use with no credential, comma separated. Unset means /plex-dupe-keep; empty means none. A LAN caller is a private-range socket peer whose request carries no proxy header (Cf-Connecting-Ip, Cf-Ray, X-Forwarded-For, X-Real-Ip, Forwarded), so tunnel traffic never counts; a POST must be JSON. |
ADMIN_EMAIL |
The identity allowed into /share/admin*. |
Modes: off checks nothing. log allows every request but logs each one that enforce would refuse (route class, method, path, caller class loopback/lan/public/unknown from the socket peer (never the address), which credential was missing; never a secret). enforce answers 403.
A request passes with any of: a valid Access JWT (signature, expiry, issuer and one of the AUDs checked), Authorization: Bearer <token>, or HTTP Basic on /webhook/*. /health is always open; a GET report from loopback (the socket peer, never X-Forwarded-For) passes without a credential, so a job running inside the container still works under enforce (action routes, POSTs and /share never qualify); /share/dl/<token> link downloads are open at the gate because the link token is their credential.
/share pages need a validated JWT in every mode, so set CF_ACCESS_TEAM_DOMAIN and CF_ACCESS_AUDS before deploying this version or friends lose access.
Action routes change things, so a request that would change something must be a POST with Content-Type: application/json (a body-less or form/text POST is refused 415, a GET 405): /verify-labels, /purge-non-radarr, /delete-paths (body {"paths": [...]}), /torrent-move, and /plex-dupe-fix?apply=1, /orphan-scan?delete=1, /retire-seeds?apply=1, /upgrade-lane-cap?apply=1, /relabel-by-plex?apply=1, /unlabel-library-seeds?apply=1, /fix-stuck-upgrade-tags?apply=1. Their dry-run reports stay on GET. Example: curl -X POST -H 'Content-Type: application/json' -H "Authorization: Bearer $TOKEN" -d '{}' '<base>/retire-seeds?apply=1'.
The Plex token is sent as the X-Plex-Token header and scrubbed from any error text.
Rollout order:
- Deploy with
APP_AUTH_MODE=logand the Access variables set. Nothing is refused; read the log forapp-auth: would refuselines to find callers without a credential. - Put a Basic user in Sonarr and Radarr's webhook connections (and the credential file named by
APP_AUTH_BASIC_FILE), put a token in each script or mover that calls the app (and inAPP_AUTH_TOKEN_FILE), and change any caller that used GET or a non-JSON POST on an action route. The token files live under the mounted/data(APP_AUTH_TOKEN_FILE=/data/app-auth-tokens,APP_AUTH_BASIC_FILE=/data/app-auth-basic), so no extra compose mount is needed; keep them mode 600. - When the log is quiet, set
APP_AUTH_MODE=enforce. Roll back by setting it tolog.
Advisory decisions for upgrade grabs, import identity and duplicate keepers (llm_decide.py, llm_advisor.py). LLM_DECISIONS=off (default) never calls a model; shadow logs what the chain would do next to what the rules did; enforce lets a confident answer (>= 0.75) override the rules. Hard rules always win. LLM_MODE_<KIND> (LLM_MODE_IMPORT_IDENTITY, LLM_MODE_DUPE_CONFIRM, LLM_MODE_UPGRADE_GATE) sets one kind on its own, so one kind can enforce while the others stay in shadow; empty follows LLM_DECISIONS, and LLM_DECISIONS=off turns every kind off. /llm-layers shows each kind's mode under modes. Set values in .env; compose passes them through with empty defaults.
GET /llm-stats?days=N (default 7, 1..90) reports per kind how many questions were answered, by which layer, why the rest were not (cold_load_timeout, warm_timeout, other_model_loaded, plex_holding_gpu, backoff, layer_down, no_layer, unparseable, other), hard-rule vetoes and agreement, with below_target flags (answered < 90%, a cause > 5%, agree < 95%, any veto); kinds below target also show on /digest.
torrent_error (LLM_MODE_TORRENT_ERROR) is shadow-only: after the Deluge error repair hands a torrent to a person (partial, library-error, missing, library-match, relink-candidate) the model picks recheck, resume, relink, wait, remove_and_research or ask from facts alone, and the answer is only logged (never acted on, even in enforce). TORRENT_ERROR_LLM_MAX (default 10) caps new questions per run; answers are cached 24 h. backtest_torrent_error.py replays JSONL fact rows against a model endpoint.
unregistered_triage (LLM_MODE_UNREGISTERED_TRIAGE, free layers only, shadow-only for now): for each torrent the unregistered sweep finds, the model picks keep / remove_keep_library / remove_and_research / ask from counts and classes (no names or paths) and the answer is only logged next to the rules' action; the rules still decide, the mass-outage guard is never put to the model, at most UNREGISTERED_LLM_MAX (default 10) new questions per sweep, answers cached 24 h.
stuck_import (LLM_MODE_STUCK_IMPORT, free layers only, shadow-only): when an importBlocked download still needs a person after the auto-import rescue, the model picks wait / retry_import / ask from classes and an age (no names) and the answer is only logged next to the rules' action (ask); the notification is sent as before. At most STUCK_IMPORT_LLM_MAX (default 10) new questions per pass, answers cached 24 h. backtest_stuck_import.py replays JSONL fact rows.
stuck_upgrade_tag (LLM_MODE_STUCK_UPGRADE_TAG, free layers only, shadow-only): when an upgrade import finds no torrent for its download id (the "upgrade tag may be stuck" notification), the model picks wait / run_sweep / ask from counts and flags (no names) and the answer is only logged next to the rules' action (ask); the notification is sent as before. Answers cached 24 h. backtest_stuck_upgrade_tag.py replays JSONL fact rows.
duplicate_folder (LLM_MODE_DUPLICATE_FOLDER, free layers only, shadow-only): for each new duplicate-media-folder finding the model picks leave / merge / ask from counts, sizes and suffix classes (no folder names) and the answer is only logged next to the rules' action (ask); the digest line is written as before and nothing is moved. At most DUPLICATE_FOLDER_LLM_MAX (default 10) new questions per scan, cached 24 h. backtest_duplicate_folder.py replays JSONL fact rows.
audit_findings (LLM_MODE_AUDIT_FINDINGS, free layers only, shadow-only): for each newly reported finding of the library seed audit and the downloads audit, the model picks fix / ignore / ask from classes, counts and sizes (no torrent names or paths) and the answer is only logged next to the rules' action (ask); the audit notice is sent as before and nothing is changed. fix is turned into ask when the follow-up is human-only (a delete, move or relabel of library files) and ignore into ask when ignoring could lose library data (both fail closed on a missing flag). At most AUDIT_FINDINGS_LLM_MAX (default 10) new questions per audit run, cached 24 h. backtest_audit_findings.py replays JSONL fact rows.
arr_health (LLM_MODE_ARR_HEALTH, free layers only, shadow-only): before each Sonarr/Radarr health push (a sustained outage, its recovery, a series or movie removed from its metadata site) the model picks notify / hold / self_heals from the event, service, check name and minutes (no titles, hostnames or URLs) and the answer is only logged next to the rules' action (notify); the push is sent as before. Hard floor: an outage at or past OUTAGE_ALERT_MIN is always notify, and a missing duration counts as past it. Fallback is notify. At most ARR_HEALTH_LLM_MAX (default 10) new questions per tick, cached 24 h. backtest_arr_health.py replays JSONL fact rows.
Both new kinds are opt-in: they stay off until their own LLM_MODE_<KIND> is set, whatever LLM_DECISIONS says, so a deploy never starts them before their back-test. Their questions are asked on a background thread after the repair or sweep finishes, one batch per kind at a time, so a cold model never delays the rules.
Layers, each skipped when its env is unset:
- Unraid Ollama (free, tried first):
UNRAID_OLLAMA_URL(e.g.http://<host>:11434),LLM_UNRAID_MODEL(defaultqwen3:14b; fixed, never auto-picked),LLM_UNRAID_KINDS(defaultimport_identity,dupe_confirm,upgrade_gate, comma-separated). Native/api/chat, no thinking, connect 2 s / total 30 s; when the model is cold (nothing loaded in/api/ps, or listed but it hasn't answered this process in the last 5 min: a listing can be a load still running or just aborted), import identity (asked from the background poller) waitsLLM_UNRAID_COLD_TIMEOUT(default 240 s) so the load fits, while grab-time kinds keep 30 s. After a timeout the layer is skipped forLLM_UNRAID_BACKOFF_MIN(default 15) minutes, doubling per timeout in a row up to 60 (an answer resets it;0turns it off), because each timed-out ask had started a model load that the hang-up aborted. Asked only when/api/psshows nothing loaded or its own model loaded (another resident model means the queue has the GPU), and when the optionalLLM_UNRAID_HOLD_URL+LLM_UNRAID_HOLD_TOKENcheck isn't holding (same contract as the local hold; the queue serves it at/api/gpu-hold?lane=unraid). When Unraid is the only free layer, a hold whose cause isplexkeeps the decision pending past the paid clock (playback ends; the next run asks Unraid again); other holds count like any other miss. Its answer counts only when, after hard rules, it is decisive (match/mismatch) at confidence >= 0.75; anything else (unsure, weak, unparseable, timeout, skipped) passes on to local Darkbloom, never straight to Claude, and doesn't start the pending clock (when Unraid is the only free layer, its misses start the same pending clock local uses). Each decision log row carriesunraid: {model, latency_ms, pass}(plushold_causeon a hold that names one) wherepassis null when Unraid settled it, elsebackoff,other-model-resident,hold,timeout,error,unparseable,unsureorweak. Skips never alert. - Local Darkbloom:
DARKBLOOM_BASE_URL+DARKBLOOM_API_KEY(OpenAI-compatible). The rule is never a switch: plex uses whatever Darkbloom has loaded and never causes a model to be loaded or swapped. It reads every id from/v1/models(cached 15 s; the list is what is loaded, and an entry markedloaded: falseor an unloadedstatuswould be ignored) and, per kind, uses the first listed id whose back-test passed for that kind (LLM_LOCAL_APPROVED_<KIND>, comma-separated,*= any). Defaults:qwen3.5-35b-a3bforimport_identityandupgrade_gate; every other kind is empty until its Studio back-test passes (backtest_local.py). Skip reasons (the layer sits out like a hold: pending clock, loglocal_skip):model-not-approved(loaded, but none approved for this kind),model-unknown(/v1/modelsunreadable or empty),model-not-loaded(the pin is not listed).LLM_LOCAL_MODELpins one model for every kind (bypasses the approved list) but it must be among the listed ids, otherwise the layer is skipped; a pin can never make Darkbloom load a model.LLM_DECIDE_URL/LLM_DECIDE_MODEL/LLM_DECIDE_KEYstill work whenDARKBLOOM_BASE_URLis unset./llm-layershas alocal_nowblock: the loaded ids and, per kind, the model it would use now or why it is skipped. Optional hold check:LLM_LOCAL_HOLD_URL+LLM_LOCAL_HOLD_TOKEN; the local layer is skipped only when the response is 200 with top-levelhold: true(errors fail open).
Approved-model variables, one per kind (all kinds, an empty value means the default above): LLM_LOCAL_APPROVED_IMPORT_IDENTITY, LLM_LOCAL_APPROVED_UPGRADE_GATE, LLM_LOCAL_APPROVED_DUPE_CONFIRM, LLM_LOCAL_APPROVED_TORRENT_ERROR, LLM_LOCAL_APPROVED_UNREGISTERED_TRIAGE, LLM_LOCAL_APPROVED_STUCK_IMPORT, LLM_LOCAL_APPROVED_STUCK_UPGRADE_TAG, LLM_LOCAL_APPROVED_DUPLICATE_FOLDER, LLM_LOCAL_APPROVED_AUDIT_FINDINGS, LLM_LOCAL_APPROVED_ARR_HEALTH.
2. Paid Darkbloom (backup only): DARKBLOOM_CLOUD_API_KEY, DARKBLOOM_CLOUD_MODEL (default qwen3.5-35b-a3b). Asked with thinking off and 2048 max tokens (with thinking on, every answer used the whole budget reasoning and was unparseable); if the server rejects chat_template_kwargs it is asked once more without it.
3. Claude: ANTHROPIC_API_KEY, LLM_CLAUDE_MODEL (default claude-sonnet-5-5), structured output via the anthropic SDK. A key that is not scoped to a workspace is refused with HTTP 400 on every call unless ANTHROPIC_WORKSPACE_ID names the workspace (sent as the anthropic-workspace-id header); a key created inside a workspace needs nothing extra.
4. Rules: an exhausted chain returns nothing and the rules action stands.
Queue layer (free, asked before layer 0, off by default): LLM_QUEUE_URL (the ollama queue's address, e.g. http://<host>:<port>) + LLM_QUEUE_TOKEN (the queue's prompt-jobs token, not its API token); with either unset the chain runs exactly as it does without this layer. Each question is one prompt job (POST /api/prompt-jobs, then GET /api/prompt-jobs/<id> every 2 s): the queue picks a free local lane, never a paid one, and reports the model that answered. The answer is kept only when that model is approved for the kind and, after hard rules, it is decisive at confidence >= 0.75. Anything else passes on to layer 0 and the layers below, which run unchanged: no answer inside the wait (LLM_QUEUE_WAIT_S; default 20 s for upgrade_gate, which is asked inline, and 90 s for the kinds asked in the background; the job is cancelled), a model that is not approved, unsure, a weak answer, an answer that is not JSON, a failed job or a queue that cannot be reached. A failure other than a non-JSON answer backs the layer off for LLM_QUEUE_BACKOFF_MIN minutes (default 10, doubling to 4x while it keeps failing). LLM_QUEUE_KINDS (comma-separated, empty = every kind with an approved model) limits the kinds asked. Approved models per kind: LLM_QUEUE_APPROVED_<KIND> (comma-separated; empty = the default below; none = the kind is not asked). Defaults: qwen3:8b and qwen3:14b for import_identity and dupe_confirm, which passed a back-test through the queue (logged questions plus known-answer control rows). Every other kind has no default, so it is asked only when its variable names a model. upgrade_gate was back-tested and not approved: both models answered allow on every control row the policy rejects, and only the hard rules caught them. The queue layer does not count as a free layer for the paid backup: on its own it never opens Claude or paid Darkbloom, and LLM_CLAUDE_ONLY leaves it out. Its step is logged as queue (model, latency_ms, pass) next to unraid, /llm-layers lists it first with queue_models, and neither the token nor the address is logged.
Claude-only: LLM_CLAUDE_ONLY=1 (also true/yes/on, default off) is for when the free layers are unavailable. With it on and ANTHROPIC_API_KEY set, Claude is the only layer built or asked (Unraid, local and paid Darkbloom are ignored even when configured), there is no pending wait, and the free-only kinds go to Claude too. The monthly USD cap, answer caches, hard rules and minimum confidence still apply, and over the cap or on errors the rules stand. Shadow mode still never spends paid calls, so it asks nothing. With the switch on but no key, a warning is logged once and only the rules run. /llm-layers reports claude_only.
Paid only as backup: with no free layer (Unraid or local) configured, no paid layer or Claude is asked and the rules stand (log error: no free layer configured). Waiting for local: when the local layer is unavailable (down, timeout, bad output, hold) the decision is pending for LLM_LOCAL_WAIT_MIN minutes (default 15) before any paid layer is used. Pending state is kept in LLM_PENDING_PATH (/data/llm_pending.json, keyed by kind + hash of the facts) so a restart keeps the clock; entries drop on resolve or after 24 h. While pending: import identity answers unsure (enforce) and dupe keeper keep_both; shadow keeps the rules action. An upgrade grab applies the rules action at once and a background thread retries local about every 60 s, then escalates; a late reject removes the torrent and a late throttle labels it (enforce only). A restart drops pending grabs and the rules action stands. A valid but low-confidence open-model answer goes to Claude immediately.
Grab-time identity check: every grab (new and upgrade, Sonarr and Radarr) is compared with the series/movie it was grabbed for, in a background thread (alert-only; nothing is removed, blocked or relabelled). Hard rules run first; if they flag it, the series' alternate titles (Radarr: alternative and original titles) are fetched and any one that passes clears it. The model is asked in the current LLM_DECISIONS mode (none when off). Tiers: hard-rule flag and the model did not say match (mismatch, unsure, pending or off) sends a Pushover "Possible wrong match" plus an identity-grab activity line; a flag the model calls match, or a model mismatch with clean rules, is an activity line only. One alert per downloadId per 24 h. GRAB_IDENTITY_CHECK=0 disables it (default 1).
Logging: each row in LLM_DECISIONS_LOG carries layer, model, latency_ms, pending_min, and for paid calls paid_calls (token usage and provider request id). Keys and headers are never logged. Each escalation to a paid layer adds an activity line (llm-escalation). GET /llm-decisions reads the log; GET /llm-spend?month=YYYY-MM sums calls and tokens per paid layer (tokens only, no prices).
/webhook/seerr syncs the import lists on MEDIA_APPROVED / MEDIA_AUTO_APPROVED. Seerr allows one webhook URL, so to keep another receiver fed set SEERR_FORWARD_URL (http or https; anything else is rejected at startup and treated as unset) and optionally SEERR_FORWARD_AUTH (the whole Authorization header value; the incoming auth is never passed on). Every POST, of any type including tests, is forwarded on a background thread with the same raw body and Content-Type (connect 5 s, total 10 s, one retry on a connection error or 5xx). The reply to Seerr never changes. One log line per forward holds the status code or error class and the notification type, never the URL, auth or body. Forwarded requests carry X-Arr-Webhook-Forwarded: 1, and a request that already has it is not forwarded again. Empty or unset means no outbound call.
arr_health.py, run from a background thread every ARR_HEALTH_INTERVAL seconds (300):
- Outages: Sonarr/Radarr not answering, their indexer, download-client and root-folder health checks, and Deluge not answering. One Pushover after 30 minutes down, one more on recovery. Short blips never push; an outage not seen for 30 minutes (e.g. the container was off) starts its clock again.
- Removed from TheTVDB / TMDb: the removed-series/movie health checks. The first read per arr is a silent baseline; each newly removed item pushes once.
- Broken library files: every
ARR_BROKEN_INTERVALseconds (21600), the arrs' error logs are read for "Unable to parse media info from file". Each file still lacking media info is rescanned, then confirmed on a pass at least an hour later. Files changed in the last hour are left alone (may still be copying), files that read fine again are dropped, and a file is only looked at again after a newer error. WithARR_HEALTH_APPLY=1(off by default) a confirmed file's source torrent is force-rechecked in Deluge when Deluge still has it; otherwise, or if the recheck didn't fix it, the file is deleted through the arr and a search is started. Unmonitored items are never deleted, at most 3 are replaced per pass, and more than 5 broken at once changes nothing and pushes once (looks like a mount or ffprobe problem). Without apply,/digestshows what apply would do for each file.
State: ARR_HEALTH_STATE (/data/arr_health_state.json). Outages and broken files also show in /digest and the activity log (arr-health).
deluge_trim.py (pure planners), wired in arr-webhook.py:
- Upgrade-lane cap (
UPGRADE_LANE_MAX, default 10 = Deluge's active-download slots,0= off). The lane is every unfinished torrent labeledradarr-upgrade,sonarr-upgradeor their-recentvariants. Anything that has downloaded a byte (or whose progress Deluge can't report) is always kept, even over the cap. Untouched torrents (0 bytes) are kept in run order (already in a download slot, then-recent, then Deluge queue position, then oldest) until the lane holds the cap; the rest are removed from Deluge with their (empty) files left alone. Runs hourly, right after the monthly cycle's relabel, and on each throttled upgrade grab (a grab landing in a full lane is dropped at once). The upgrade search is a refill, not a standing queue: it skips its poll while the lane is full (or Deluge can't report it), and otherwise searches at most as many items as there are free slots, so each finished upgrade makes room for the next one. Radarr/Sonarr find dropped upgrades again on later searches. Preview:GET /upgrade-lane-cap; trim now:POST /upgrade-lane-cap?apply=1. - Seed retirement (
SEED_RETIRE_DAYS, default 180,0= off). Finished torrents labeledsonarr,radarr,lidarr,library-seedor an upgrade label (SEED_RETIRE_LABELSoverrides) that have seeded at least that many days in a swarm with more thanSEED_RETIRE_MIN_SWARM(5) other seeds stop seeding, longest-seeded first, at mostSEED_RETIRE_PER_RUN(100) a day. Idle rule (SEED_IDLE_DAYS, default 14,0= off): a torrent on those labels that has uploaded nothing for that many days (Deluge'stime_since_upload; never uploaded counts as idle, unknown never does) retires once it has seededSEED_IDLE_MIN_DAYS(default and minimumSEED_DAYS, 21), so quiet seeds go early and ones still uploading keep seeding untilSEED_RETIRE_DAYS. Same swarm rule; aged-out torrents go first, then the longest idle. Earner set (SEED_KEEP_TOP_EARNERS, default 30,0= off): the labeled torrents with the mosttotal_uploadedare never retired here and never unseeded by the weekly stalled-seed review, to keep ratio and bonus points growing; the preview reportskept_earners. The preview shows each candidate'srule,idle_daysandratio. The download copy is deleted only when the library verifiably holds every video;library-seedtorrents always keep their files. When files are kept (here or in any other keep-data removal), the torrent's own samples and release clutter (.nfo,.txt,.sfv,.srr, links, Proof/Screens pictures:episode_retention.is_junk) are deleted right after the entry goes, leaving videos, subtitles and artwork; nothing is deleted for a cross-seed still loaded, a torrent with no main video, or a junk file over 50 MB. Unlabeled and other labels are never touched.remove_torrent'sSEED_DAYSfloor still applies. Preview:GET /retire-seeds; one batch now:POST /retire-seeds?apply=1.
Both record a cleanup line in the activity log when they remove anything.
stuck_plan.py (pure planner), wired in arr-webhook.py. Every STUCK_CHECK_INTERVAL seconds (default 600) it looks at unfinished torrents with a normal sonarr or radarr label. Unlabeled torrents, library-seed, other labels and anything finished or seeding are never touched.
A torrent is stalled when its state is Downloading, it moves under 1 KiB/s, and it has not downloaded for STUCK_AFTER_MIN minutes (default 20; a time_since_download of -1 counts only once the torrent has been active that long). The ladder, per stalled torrent:
- Force a reannounce and move it to the top of the queue.
STUCK_AFTER_MINlater, if still stalled: pause, then resume. Every stalled torrent is diagnosed first from what Deluge reports, andGET /stuck-downloads, the dry-run lines and the digest carry the diagnosis. A release is removed only when it could never complete.
What Deluge reports (from deluge/core/torrentmanager.py on_alert_tracker_*, deluge/core/torrent.py; 2.1.1 is identical to develop):
| Field | Values | Meaning here |
|---|---|---|
tracker_status |
Announce OK |
tracker working |
Warning: <msg> |
tracker answered with a warning: working, the text stays on the row | |
'' or Announce Sent |
not announced yet: no conclusion, no tracker report, no never-complete clock | |
Error: <msg> |
set only when no endpoint of that tracker works. torrent_is_unregistered is asked first (unregistered: left to the unregistered sweep), otherwise tracker error: reannounce, never blocklisted. One report per host, only after that host was in Error: on 2 passes in a row |
|
| anything else | no conclusion, logged once | |
total_seeds |
tracker num_complete, -1 unknown |
0 (not -1) is required for never-complete |
pieces (_get_pieces_info) |
per piece 3 done, 2 downloading, 1 a connected peer has it, 0 no connected peer has it; none when seeding or no metadata | read per hash, only for stalled candidates with 0 seeds; only the count of state-0 pieces is kept |
Diagnoses: unregistered, tracker error, pending, local (tracker working and seeds reported, or every missing piece is at a peer: uncap, reannounce, restart, notify once, never blocklisted), unknown swarm (seeds -1 or pieces unreadable: reannounce only) and never complete (tracker working, total_seeds == 0 and at least one state-0 piece, on every pass for the whole STUCK_GIVE_UP_HOURS window; any other observation resets the window). Queued or paused time does not count.
- After
STUCK_GIVE_UP_HOURS(default 6) of never-complete, at any progress (there is no 95% exception, and manual grabs and season packs follow the same rule): if the release is in a Sonarr/Radarr queue, blocklist it there (removeFromClient=false,blocklist=true); remove the torrent and delete its files (the library guard still keeps files in library paths; this path alone skips the upload-based seed floor for a torrent that never finished, viaremove_torrent(never_finished_ok=True)); then runEpisodeSearch/MoviesSearch. A torrent in no arr queue is still removed, and the digest says it was not blocklisted. One digest line per removal: name, percent, seeds, pieces no peer has, hours, blocklisted yes/no, files deleted or kept by the library guard. Indrymode:[dry] would remove ..., once per torrent.
A torrent that moves again starts over. The ladder is kept in STUCK_STATE_PATH (/data/stuck_state.json) in on mode so a restart does not reset it.
Upgrade-lane torrents are not on the ladder. Each one gets a per-torrent connection cap (UPGRADE_MAX_CONNECTIONS, default 10) so the 30 KiB/s upgrade torrents do not hold every peer slot; the cap is cleared when a superseded torrent is released.
STUCK_AUTOMATION is off, dry (the default, also for any other value) or on. off does nothing on the timer. dry logs and writes stuck-downloads activity lines only: no call is made that changes Deluge or the arr apps (the connection cap included), and no state is saved. on carries the actions out. Preview: GET /stuck-downloads (read-only; each torrent, its step and what the next pass would do).
watch_hold.py (pure) is wired in arr-webhook.py. When an upgrade replaces a file someone is watching, or has a resume point in, the switch should go unnoticed: the import never happens under a stream, and afterwards each Plex user resumes at the same moment of the new copy, with the same audio and subtitle choices.
How it works, per upgrade download (a Sonarr/Radarr download that replaces an existing file):
- Track. Every minute the webhook reads the arr queues (rows downloading or import pending) and the upgrade lane (labels
radarr-upgrade/sonarr-upgradeand their priority variants, and glacier-held downloads), and records the file being replaced and its Plex item. - Snapshot. While nobody is streaming it, it reads each Plex user's view of the old item: resume point, last viewed, selected audio and subtitle tracks (non-default picks only). The snapshot is taken again after each stream, and when it is older than 30 minutes.
- Hold. A download with a normal
sonarr/radarrlabel is moved to thewatch-holdlabel when the item is streamed (now or in the lastWATCH_HOLD_QUIET_MINminutes), or when it isWATCH_HOLD_AT_PCT% done and a resume point needs mapping. Like the glacier hold, the arr stops seeing the download but keeps its Grabbed history, so the release restores the label, the arr re-tracks it and imports it as the upgrade of its grab. Upgrade-lane downloads are not relabelled: auto-rescue skips them while they are held (watch_holdin its skip counts), and a glacier hold is kept past its own release until watch hold lets go. - Map. Once the download is complete and nobody is watching, each resume point (at least 30 s in, before 95% of the runtime, viewed in the last
WATCH_HOLD_STALE_DAYSdays) is mapped to the new file by its sound: 40 s of audio around the point, decoded at 8 kHz mono, is matched by loudness envelope (normalised cross-correlation) within ±120 s, then ±300 s, of the new copy, at the same speed and at the PAL speed-up either way. A second window 150 s earlier (or 90 s later) must land within 0.5 s of the same shift. A point that does not match well is not mapped. Only one download is mapped per pass. - Release. The hold ends when nobody is playing it, nobody has for
WATCH_HOLD_QUIET_MINminutes, the snapshot is fresh and every point is mapped, or afterWATCH_HOLD_MAX_HOURSfrom completion (a download never seen complete gets 7 days more). The cap only skips the snapshot and the mapping: nothing is released while the item is playing or paused, or withinWATCH_HOLD_QUIET_MINof its last stream, however long that takes. A stream is never cut or switched; the old file keeps playing until the viewer stops. - After the import. It waits up to 10 minutes for Plex to list the new file, then for each user: writes the mapped resume point (only when the shift is at least 1 s, and only if the user's point has not moved more than 5 s since the snapshot), puts back the old point when Plex made a new item and no point was mapped, and selects the matching audio track (same language and commentary, then codec and channels) and subtitle track (or off; forced subtitles are never turned off).
The sound is read with ffmpeg under the name watch-align, which tierfs treats as a background reader (remote reads, no promote).
Usenet (SABnzbd). A paused job never finishes, so a Usenet upgrade is not held by pausing it. With WATCH_HOLD=on, scripts/setup-usenet-arrs.py sets the SABnzbd client's recent and older priority to Paused in both arrs (Radarr recentMoviePriority/olderMoviePriority, Sonarr recentTvPriority/olderTvPriority; the Paused value is read from the app's own field options), so every grab arrives paused. Each pass (and the Grab webhook) then looks every undecided paused job up in the arr's queue by its download id, once:
- Not an upgrade (the item has no file): the job is resumed, nothing else changes.
- An upgrade: the job is moved to the
watch-holdSABnzbd category (own folder under the complete folder, defined byusenet/render_sabnzbd_ini.py) withchange_cat, which works only on a queued job, and then resumed. The arr's category is kept as the way back. In that category the arr cannot see the job, and it downloads to completion like any other. - While it is held and complete, the new file is found and every resume point is mapped as for a torrent.
- Release is an import, never an import under a stream. The sessions are read again right before the command, also at
WATCH_HOLD_MAX_HOURS(the cap skips the mapping, never the stream check). The import is the arr's own scan command (DownloadedMoviesScan/DownloadedEpisodesScan) withpaththe completed folder as the arrs see it (SABNZBD_COMPLETE_DIRmapped toSABNZBD_ARR_VISIBLE_DIR),downloadClientIdthe job id as SABnzbd spells it andimportModeMove. It is verified in the arr's history (or by the old file having been replaced) and retried up to 3 times, 2 minutes apart; only then is the SABnzbd history entry deleted with its files. The after-import writes of the previous section then run as for a torrent. - A held job that fails in SABnzbd is marked failed through the arr's
history/failed/{id}for its grab, so the release is blocklisted and searched again. - A job already in SABnzbd's history when first seen cannot be held and is imported by the arr as usual; it is only counted (
usenet_late). - With
WATCH_HOLDnoton, the setup script puts a Paused priority back to Default, so no job waits for a hold that is not running. Switching the hold off later puts queued held jobs back to their category; run the setup script again, and resume any job still paused in the SABnzbd queue. - In
drymode nothing is changed in SABnzbd or the arrs; the passes only count (would_hold,would_resume,would_release).
WATCH_HOLD is off, dry (the default, also for any other value) or on. dry does the reads, the snapshots and the mapping and logs what it would do ([watch] dry ... would_hold, would_wait_<reason>, would_write_offset, would_write_picks), but never relabels a download, never delays an import and never writes to Plex. off releases any hold left from on. Logs carry counts and infohashes only; Plex tokens are never logged or stored.
Not covered yet:
- Downloads on a remote seedbox: held and choices carried over, but no resume point is mapped (the new file is not local until it is moved).
- Season packs: held and choices carried over, but no resume point is mapped.
- While a download is held (torrent or Usenet) the arr does not see it in its queue, so it could grab another release of the same upgrade; the dedupe passes do not look at the
watch-holdlabel. Deluge has no guard against this and none was added for Usenet. - A held download is off the stuck-download ladder until it is released.
- Offloaded old files: the webhook does not mount tierfs yet, so an old file that is only on the remote tier cannot be read; its download is released at
WATCH_HOLD_MAX_HOURSwithout a mapped point.
| Key | Default | Meaning |
|---|---|---|
WATCH_HOLD |
dry |
off, dry or on |
WATCH_HOLD_QUIET_MIN |
10 |
minutes since the last stream before an import may happen |
WATCH_HOLD_STALE_DAYS |
30 |
resume points viewed longer ago are not mapped |
WATCH_HOLD_MAX_HOURS |
48 |
longest hold after the download completes |
WATCH_HOLD_AT_PCT |
50 |
progress at which a download with a resume point to map is held |
WATCH_HOLD_STATE |
/data/watch_hold_state.json |
holds, tracked downloads and recent streams |
Every other path that deletes or unlinks a library file asks Plex first, with the same file-name match and WATCH_HOLD_QUIET_MIN window as watch hold. A file a viewer is on is left in place and tried again on a later pass:
| Path | While someone plays the file | Plex unreadable |
|---|---|---|
Glacier release, dropping the - glacier-tmp stopgap link |
release waits ([watch] guard glacier_link_playing) |
releases as before |
/plex-dupe-fix?apply=1 (and the daily run) |
loser kept: skipped: playing now; next run |
nothing deleted |
arr health broken-file repair (ARR_HEALTH_APPLY=1) |
waiting: someone is playing it |
waits |
/orphan-scan?delete=1 |
counted in skipped_playing |
nothing deleted |
/delete-paths?apply=1 |
listed under skipped |
nothing deleted |
Dry runs never ask Plex. STREAM_GUARD=off turns the guard off (default on). The offload tier has its own check (open file handles and Plex sessions), and downloads-only cleanups never touch a library file, so neither goes through this guard.
abandoned_audit.py (pure) is wired in arr-webhook.py. Once a week (ABANDONED_AUDIT_INTERVAL seconds, default 604800, 0 = off; checked on the 6h maintenance tick, measured from the saved report so a restart does not rerun it) it compares what is on disk (Downloads and the library roots) with Deluge, Plex and Radarr/Sonarr and lists what nobody owns. Report only: it never deletes, moves, relabels or removes a torrent. Logs carry counts and GB, never paths; the paths appear on /digest and /abandoned-audit.
A file is known when its path, or its (basename, size), appears in Deluge's file lists, Plex's media parts or the arrs' file records (the basename+size rule covers a different mount prefix per container). Anything newer than 24 h, or in a torrent under 100%, is skipped.
| Bucket | What it lists | Needs |
|---|---|---|
downloads_orphan |
a Downloads file no torrent owns (same rule as the Downloads audit) | Deluge |
library_untracked |
a video under a library root unknown to Plex, the arrs and Deluge (Plex local extras such as Trailers/ or *-trailer.mkv are left out) |
Deluge, Plex, arrs |
library_no_video_dir |
a library folder with no video anywhere below it (leftover subtitles, nfo, art) that is not a Radarr movie folder or Sonarr series folder; size is the folder total | arrs |
torrent_not_in_library |
a finished sonarr*/radarr* torrent seeded 21+ days whose videos neither Plex nor the arrs know and that all have a single link. The reason says whether a library file has the same size (likely imported as a copy) or not (check for a failed import) |
Deluge, Plex, arrs |
plex_missing_file |
a Plex part whose file is not on disk (listed, no bytes, not in the totals) | Plex |
Reading the report. size is the row's bytes; reclaim_bytes is what deleting it would actually free. A hardlinked file frees space only when every link of it was found in the scan and every one of them is listed; otherwise it is 0, and one inode is counted once in the totals. If a source could not be read (sources shows failed), every bucket that needs it is incomplete with no rows: a file is never called abandoned because a source failed. Each bucket keeps its 500 largest rows but counts all of them. A library root that does not exist is listed under missing_root. walk_errors counts folders that could not be read.
GET /abandoned-audit returns the saved report; ?run=1 runs now and saves it; ?run=1&dry_run=1 runs now and saves nothing. The /digest page shows the last run, source status, one line per bucket and the 20 largest rows of each.
| Key | Default | Meaning |
|---|---|---|
ABANDONED_AUDIT_INTERVAL |
604800 |
seconds between runs, 0 = off |
ABANDONED_AUDIT_STATE |
/data/abandoned_audit.json |
the latest report (safe to delete) |
ABANDONED_AUDIT_ROOTS |
the library roots | comma-separated library roots to scan |
Runs on Unraid at /mnt/user/appdata/plex-automation, on the br0 macvlan network (external) at a static IP. .env lives only on the server and is gitignored — never commit real secrets.
GitHub Actions (.github/workflows/ci.yml) runs on every push/PR to main: syntax + ruff lint check on all Python scripts, then a Docker build to make sure the image actually builds.
-
Watch hold (
watch_hold.py, see Watch hold): an upgrade is not imported while its item is streamed or was in the last 10 minutes; each Plex user's resume point is mapped to the new file by matching the sound around it, and written back with their audio and subtitle choices after the import.WATCH_HOLD=off|dry|on, defaultdry(reads and maps, logs what it would do, changes nothing). The image getsffmpeg(run aswatch-align, which tierfs now treats as a background reader by default) andnumpy. Glacier release gains akeephook so a glacier hold waits for watch hold. Newtest_watch_hold.py. -
Stuck downloads (
stuck_plan.py, see Stuck downloads): stalled sonarr/radarr torrents go up a ladder (reannounce + queue top, pause + resume, then, only for a release that could never complete (no seeds and a piece no peer has, for the whole window), blocklist in the arr, remove the torrent and its files, and search again, at any progress). Upgrade-lane torrents get a per-torrent connection cap.STUCK_AUTOMATION=off|dry|on, defaultdry. Preview at/stuck-downloads. -
Deluge trimming (
deluge_trim.py, see Deluge trimming): the upgrade lane is capped atUPGRADE_LANE_MAX(10) unfinished torrents. Untouched overflow is removed hourly, after the monthly relabel and at grab time, and the monthly search skips while the lane is full; torrents with any progress are never dropped. This trim is deliberate, unlike the 2026-09-26 queue-wipe incident. Long-seeded torrents on managed labels retire afterSEED_RETIRE_DAYS(180), idle ones (no upload inSEED_IDLE_DAYS, 14) afterSEED_DAYS(21), in swarms with more than 5 other seeds, 100 a day, download copy deleted only when the library holds every video. Previews at/upgrade-lane-capand/retire-seeds. Newtest_deluge_trim.py. -
Sonarr/Radarr health automation (
arr_health.py, see Arr health): Pushover for outages over 30 minutes (arrs, indexers, download clients, root folders, Deluge) and their recovery, and for items newly removed from TheTVDB/TMDb (first read baselines silently). Broken library files (media info unreadable) are rescanned, confirmed an hour later and listed in/digest; only withARR_HEALTH_APPLY=1are they repaired (Deluge recheck of the source torrent, else delete through the arr + search; unmonitored never deleted, 3 per pass, more than 5 at once changes nothing). Newtest_arr_health.py. -
Import identity title guards and local model approval. Two new hard rules turn a model's
matchintounsure:spinoff_title_reverse(Sonarr: the matched title extends the release's name, e.g. anNCISrelease matched to NCIS: Origins) andtitle_first_word(release name and matched title start with different words, articles skipped). On the 340 real identity cases they flag 0 of 150 true matches and all 4 false matches qwen3.5-35b-a3b made. The local Darkbloom layer now only uses an auto-picked model on its kind's approved list (never a swap), re-reads the loaded model every 15 s instead of 10 min, and the Unraid layer waits up toLLM_UNRAID_COLD_TIMEOUT(120 s) for import identity when nothing is loaded. -
Library RAR sets (Plex can't play
.rar). Newrar_extract.py+ theunarpackage in the image. Each library RAR set no torrent owns is checked withlsarand the owning Sonarr series / Radarr movie (folder match): delete the volumes when the *arr already has a file for every episode/movie inside (first volume last, so a retry can still list it), unpack in place when any is missing (temp folder, moved in only on success, volumes deleted last, then an *arr rescan), and skip (parked asskipped, nothing touched) when unsure: no video inside, no SxxEyy or NxNN (3x01,3x01-02) in an inner name, an episode Sonarr doesn't list, or no owning item. lsar/API errors retry up to 3 times, thenfailed. Sets come from keep-data torrent removals and fromGET /rar-library-scan(dry run: each set with its action and reason) /POST /rar-library-scan?apply=1(queues only unpack/delete sets); queue atGET /rar-extract-queue. The daily unpacked-torrent cleanup now ages out every RAR torrent (Deluge file list has RAR volumes and no main video), library seeds included, atSEED_DAYS.RAR_EXTRACT_ENABLED=0turns the worker off. Newtest_rar_extract.py,test_rar_set_action.py. -
Stop Sonarr/Radarr imports from moving files out of Deluge torrents. Every import command arr-webhook sends (ManualImport in the importBlocked poller, the revive rescan, auto-rescue) now uses
importMode: 'copy';autoMOVES the file when the *arr has no tracked download for it, which left torrents with missing data ("Missing or invalid torrent data!"). Copy hardlinks here (copyUsingHardlinks). Newrestore_moved_files()self-heals past moves: it reads *arrdownloadFolderImportedhistory and hardlinks the library file back into the live torrent (never copies, deletes or overwrites; size must match), runs everyRESTORE_MOVED_INTERVAL(900s), fromdeluge_error_repairfor errored torrents, and via/run-restore-moved(?dry_run=1,?lookback_days=N). A restored torrent Deluge had written off (Queued/Paused/Downloading below 100%) is force-rechecked (no pause) so it doesn't re-download over the hardlink. Needs the new compose mount/mnt/user/data:/srv/data(hardlinks cannot cross mounts); envRELINK_DATA_ROOT(default/srv/data) andRESTORE_MOVED_FILES(default on,0disables). -
Library-seed guard (Deluge plan U1, F1/F2): never move or data-delete a torrent whose Deluge
save_pathis inside the Plex library (LIBRARY_ROOTS:/data/Media/Movies,/data/Media/TV Shows,/data/Media/TV Shows - Asian; normalized, case-insensitive prefix match via newis_library_path).supersede_torrentnow readssave_path(new read-only_torrent_save_path,core.get_torrents_status) after relabeling and, for a library path, recordssupersede-library-seedand returns without the in-flight release or themove_storagetoSEEDING_DIR(moving it would pull the live media out of the library).remove_torrent(remove_data=True)fetchessave_pathalongsidetracker_status/seeding_time(or probes it when the caller's info lacks it) and, for a library path, downgrades toremove_data=Falseand recordslibrary-guardbefore the HnR check. Fail-safe: a failed probe returnsNone, which falls through to the existing behavior and existing guards; the guard only ever removes a move/delete, never adds one. Always on, no flag. Newtest_library_guard.py. -
Fix the supersede workflow leaving 0%/paused "superseded" orphans (the pile seen after a reboot recheck).
supersede_torrent()calledcore.move_storageafter the *arr upgrade import had already deleted/overwritten the old file, so a fileless torrent was relocated toSEEDING_DIRwhere it sat at 0% forever — never accruingseeding_time, socleanup_superseded(gated on the seed window) could never reap it. Two fail-safe guards:supersede_torrentnow probestotal_done(new_torrent_has_local_data) and only moves when data is actually present, else it labels the torrent superseded but skips the move and recordssupersede-no-data; andcleanup_supersededgained an orphan reaper that removes a 0%-no-data superseded torrent withremove_data=False(a true orphan has no files to leave; a mount-race false 0% can't delete real bytes), gated on amount_healthycheck so the shfs mount-race signature — every torrent reading 0% — can never trigger mass removal. The primary data-preservation fix is the *arr config already applied (Use Hardlinks + Completed Download Handling Remove=No), which keeps the download inode alive through import; these guards make the automation self-healing when that slips. Newtest_supersede_orphan.py. -
Dedupe throttled upgrades at grab time instead of only on the daily/weekly sweep.
handle_grab()relabels a throttled upgrade out of the *arr's own download-client category, which is what blinds the *arr'sQueueSpecificationand lets it grab a second release of the same film — the scheduled passes did catch that, but the duplicate could burn bandwidth for up to a day first. Newdedupe_grabbed_release()runs the existing pass immediately, scoped to the one movie/series just grabbed, so the second copy is dropped before it has really started. It is called after the relabel +queue_bottom, which is the earliest point the new torrent is observable to the pass at all (the pass looks in the-upgradelane; while the *arr's queue record is still stale-visible the existingqueue_hashescheck stops it being counted twice). The remaining race is the *arr's own history — the Grab webhook can beat thegrabbedrecord being queryable bydownloadId— so the identity is polled for (GRAB_DEDUPE_TRIES, default 6,GRAB_DEDUPE_DELAYs apart, default 5) rather than slept on, and if it never resolves nothing is touched. Implemented by givingcleanup_radarr_queue_dupes(movie_id=None)/cleanup_sonarr_queue_dupes(series_id=None)an optional scope rather than writing a second copy of the logic; scoping narrows what is compared, not what is read, and every safety property is unchanged — Sonarr in particular still keeps its episode-set identity with subset-only elimination inside the series, so a different episode of the same series is never removed. Both passes now run under a shared reentrant lock, since two Grab webhooks for the same movie arrive on separate threads seconds apart and interleaved passes reading either side of a write could otherwise pick different keepers and remove both copies. The daily and weekly schedulers are unchanged and remain the backstop. Newtest_grab_dedupe.py. -
Add the Sonarr counterpart of the queue dupe pass, which never existed:
cleanup_sonarr_queue_dupes(). Sonarr has the identical blind spot (Deluge.GetItems()→GetTorrentsByLabel(TvCategory)), so a throttledsonarr-upgradetorrent leaves/api/v3/queuethe momenthandle_grab()relabels it — and unlike Radarr, nothing was policing that population from either side. Candidate set is the Sonarr queue plus the in-flight throttled lane, identity for lane torrents coming from/api/v3/history?downloadId=. Identity is where the two services differ: a movie is onemovieId, but a TV grab covers a set of episodes (single episode, multi-episode file, or season pack), soseriesIdis not an identity — two different episodes of one series are not duplicates. Sonarr also emits one queue record per episode, so a season pack's records are folded back into a single candidate before anything is compared. A candidate is dropped only when its episode set is a subset of a keeper's, so the keeper delivers everything the loser would; keepers are chosen by coverage first (dropping a 10-episode pack to keep one higher-scoring episode inside it would leave nine episodes with nothing in flight), then custom-format score, then bytes already pulled. Straddling packs (S01E01-05vsS01E04-10) are both kept. Same safety properties as the Radarr pass: finished/seeding torrents are never touched, queue-record losers go through the queue API withblocklist: False(bulk endpoint, since a pack is many records), lane losers are relabeledsupersededforcleanup_superseded, and each removal is individually wrapped. Runs on the same daily and weekly schedulers as the Radarr pass. Newtest_sonarr_queue_dupes.py. -
Fix upgrade grabs never reaching import (Spider-Man: Brand New Day, 2026-10). Three defects: (1)
supersede_torrent()only relabeled, so a duplicate loser that was still downloading kept its throttled-lanemax_download_speedcap (it persists after relabel because thesupersededlabel hasapply_maxoff) and crawled forever -- it now keeps thesupersededlabel, clears the per-torrent cap and resumes it if paused, never removes it or its data, and lets it finish and seed untilcleanup_supersededreaps it afterSEED_DAYS(partial downloads are not moved mid-download; the Queued-at-0% reaper is unchanged). (2) The dedupe passes nowqueue_topthe surviving keeper so it is not starved at the bottom of the queue by the losers. (3)dedup_via_radarrno longer supersedes a finished upgrade that Radarr grabbed withinPENDING_IMPORT_GRACE_HOURS(48) and has not imported yet -- superseding hid it from Radarr and auto-rescue. The Sonarr dedupe paths (dedup_via_sonarr: pack-vs-singles, singles-vs-pack, same-season packs, per-episode losers) get the same pending-import protection via_sonarr_import_pending. Newtest_supersede_inflight.py,test_sonarr_pending_import.py. -
Fix the duplicate-grab check being structurally blind to the exact downloads it polices.
cleanup_radarr_queue_dupes()grouped/api/v3/queuerecords bymovieId, but Radarr's Deluge client only reports torrents carrying its configured category label (Deluge.GetItems()→GetTorrentsByLabel(MovieCategory)), so the momenthandle_grab()relabels a throttled upgrade fromradarrtoradarr-upgradethe torrent leaves the download-client item list and its queue record disappears. Every throttled upgrade was therefore invisible: the pass saw one entry per movie and removed nothing, while Deluge sat on two 0%-complete releases of the same film. (The same blind spot defeats Radarr's ownQueueSpecification, which is why the second release gets grabbed at all.) The candidate set is now the queue plus in-flight torrents in the throttled lane, whosemovieIdand custom-format score come from Radarr's grab history (/api/v3/history?downloadId=). Losers with a queue record are removed via the queue API as before; losers without one are relabeledsuperseded, handing them to the existingcleanup_supersededpath instead of deleting data out from under the tracker. Finished/seeding torrents are never touched (hit-and-run), score ties break toward whichever has already pulled bytes, and each removal is now individually wrapped so one failure can't abort the rest of the pass. Newtest_queue_dupes.pycovers it with mocked Radarr/Deluge responses. -
Stalled-seed cleanup now unseeds instead of deleting, and covers labeled library-seed torrents.
remove_torrent()gained aremove_dataparameter (defaultTrue, unchanged for every existing caller);cleanup_stalled_seedspassesremove_data=Falseso a qualifying torrent stops being tracked/seeded by Deluge but its file(s) are left untouched on disk — required since a library-seed torrent's seeded file IS the live Plex media. Scope is now every labeled torrent (includingLIBRARY_SEED_LABEL, the actual intended target); unlabeled/unmanaged torrents are skipped entirely. -
Stalled-seed cleanup: add a swarm-safety gate before removal. A torrent now also needs the tracker-reported
total_seeds(swarm-wide, not our connected-peer count) to be greater thanSTALL_MIN_SWARM_SEEDS(env, default 5) on top of the existing staleness + negligible-upload checks, so removing our copy never drops availability. Iftotal_seedsis unknown (tracker hasn't scraped yet — libtorrent reports-1, or the field is missing), the torrent is left alone rather than treated as safe to remove./run-stalled-seedspreview output now includesswarm_seedsper candidate. For the "old library-seed torrents sitting around for months" use case, setSTALL_SEED_MIN_DAYS=180(6 months) at deploy time — the code default (21) is unchanged and not overridden anywhere indocker-compose.yml/.env.example, so this is a manual deploy-time change. -
Add
scripts/set-min-seeders.sh: idempotent bootstrap that sets Minimum Seeders (default 5) on every torrent indexer in both Radarr and Sonarr — stops grabbing 1-seeder releases that stall and feed the importBlocked/dupe pattern. -
importBlocked poller: send Sonarr's
includeUnknownSeriesItemsqueue param alongside Radarr'sincludeUnknownMovieItems(each app ignores the other's), so unknown-series stuck items are visible to the Sonarr check too. -
media_share.pymajor overhaul: FTPS (FTP over TLS) support viaftplib.FTP_TLSin addition to SFTP; protocol dropdown in admin + self-service settings forms. Global rate limit now shared across all concurrent uploads (module-level token bucket) instead of per-friend. Poster grid UI for Movies and TV pulling metadata + posters from Radarr/Sonarr APIs instead of raw file listing; Music keeps file browser. Per-title access control: admin can restrict each friend to a specific subset of movies/shows via a searchable checkbox page at/share/admin/friend/<id>/titles. Self-service settings page at/share/settingsso friends can update their own FTPS/SFTP destination without involving the admin. Usage page now shows an admin-wide breakdown table (all friends × all periods) for the admin, and per-user detail for regular friends. Admin friends table shows total data sent per friend.Media Shareheader links back to/share. Connection test handlessocket.timeoutexplicitly with a clear "timed out after 10s" message. -
Queue all upgrade-labeled torrents (
sonarr-upgrade/radarr-upgrade) to the bottom of the Deluge queue immediately on grab, and re-enforce top/bottom ordering every hour inprioritize_normal_torrents()— previously a newly-grabbed upgrade kept whatever queue position Deluge assigned it until the next monthly relabel cycle, so some upgrades queued ahead of others inconsistently. -
Add
media_share.py: friend-facing media portal at/share— browse/download (resumable) from Movies/TV/Music libraries; push files/folders to a per-friend SFTP destination; admin panel at/share/admin(visible only toADMIN_EMAIL) to manage friends, SFTP creds, per-library access, and per-friend rate limits entirely online with no restarts; SQLite-backed usage tracking; clean dark-theme UI. -
Run the Flask dev server with
threaded=Trueso a slow synchronous webhook handler (e.g.handle_upgrade_importwaiting on Deluge) can't briefly block other incoming Sonarr/Radarr webhooks. -
Fix potential
AttributeErrorinhandle_grab()/handle_upgrade_import()(arr-webhook.py) when Sonarr/Radarr sendsdownloadId: null—.get('downloadId', '')doesn't substitute the default for an explicitnullvalue, only a missing key. -
Fix
NameError: name 'removed' is not definedinmonthly_upgrade.pywhen no torrents qualified for purging —removedwas only initialized inside theif to_remove:block, crashing the script before it could reach the search/relabel steps. -
Fix Radarr bulk search (
radarr_bulk_search()inarr-webhook.py, Step 2 ofmonthly_upgrade.py) sendingmovieIds: []to theMoviesSearchcommand — Radarr treats that as a no-op. Now fetches all monitored movie IDs first and passes them explicitly. -
Add
requirements.txt, GitHub Actions CI (lint + Docker build), and this README. -
Initial public release: stripped a shared personal "monitor" stack down to just the Sonarr/Radarr/Deluge automation (
arr-webhook.py,monthly_upgrade.py); the unrelated reddit/BTC/XMR monitors were split out to a separate project.