Skip to content

fix(downloads): stop preparing a file once no download needs it - #4085

Merged
Quick104 merged 5 commits into
Silo-Server:mainfrom
Rhainland:fix/998-orphaned-artifact-prep
Nov 14, 2026
Merged

Quick104 merged 5 commits into
Silo-Server:mainfrom
Rhainland:fix/998-orphaned-artifact-prep

Conversation

@Rhainland

@Rhainland Rhainland commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #998
Related issue: N/A
Validation tasks: none (the server downloads task #1168 has no recorded results)

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

When a user deletes a download while the server is still preparing its file, the transcode keeps running to the end, and a job still waiting in the queue starts later anyway. Nobody receives the result, but it costs CPU or GPU time, source reads and preparation slots. This change stops a queued or running preparation as soon as its last waiting download is gone. A job that another download still waits on keeps going.

#1468 already stopped missing-output recovery from rebuilding unused ready files. This PR covers the rest of #998: work that is queued or running when its last download is deleted, revoked or moved to another quality.

Approach

A job no in-flight download needs is retired: the row becomes expired, as #1468 does for unused ready files, and keeps its recipe. Deleting a download, an administrator revoke, a managed quality change, and a late completed report retire the old job right away. The check that no other in-flight download needs the job runs in the same statement. An encode running on the same replica stops at once. One running on another replica or a transcode node stops at its next heartbeat, because the heartbeat only renews a running job.

Jobs that no in-flight download needs and that nothing has used for ten minutes count as abandoned. The claim query skips them, their worker's next heartbeat fails, and the preparation run, every 30 seconds, retires them. The heartbeat matters on a busy server, whose preparation run waits for its own running encodes. Asking for an expired file again counts as a use. This catches downloads removed some other way, such as a deleted profile or monitor, and orphaned jobs left by earlier versions. The ten minutes leave room for a create that has queued its job but not yet inserted its download row.

The job keeps its id and output path, so a retired running job keeps an unowned lease for the stopped worker's heartbeat window, as a pause does. If someone asks for the same file again within that window, the job is queued, but no worker claims it until the window ends. A new encode therefore never writes to the output path while the old one is still shutting down.

A create can read a job just before it is retired and then link its download to the expired row. Confirming the link, which every create path already does, queues the job again and starts preparation. Revoke used to delete such a job, which failed that racing download. It now uses the same retirement.

Validation

  • go build ./..., gofmt -l, go mod tidy -diff, go vet ./..., make lint-changed, make verify-local-paths, make verify-route-inventory, make verify-size-ratchet: clean.
  • make test-go: pass.
  • go test ./internal/downloads/... ./internal/apiv2/... against a freshly migrated Postgres: pass. Two new DB tests, listed in scripts/ci/db-contracts.txt, cover these cases: deleting the only download of a running job stops its local attempt and fences its heartbeat; a queued job is retired; a job shared with another download keeps preparing; a download linked after retirement queues the job again; a re-request does not claim a retired running job inside the stop window; stale orphaned jobs, queued or with a dead worker, are skipped by the claim query and retired by the preparation run, while a needed job and a just-queued job are not.
  • Review fixes, each with a test that failed before the fix: a heartbeat fails for a job no download has needed for ten minutes; a late completed report stops the job (TestLateCompletionStopsItsPreparationDB, in scripts/ci/db-contracts.txt); a requeued file is not skipped as abandoned; a retired job's finished local file is removed. ConfirmArtifactLink locks FOR NO KEY UPDATE, which avoids a deadlock reproduced in Postgres with FOR SHARE.
  • Web checks not run: no web files changed.

Evidence

Checked on a local build with a 15-minute synthetic 1080p movie and download.max_concurrent_prepares = 1. Two devices requested managed transcoded downloads, 2 Mbps and 1 Mbps, through POST /api/v2/downloads. The first job was encoding and the second was queued. Both downloads were then deleted with DELETE /api/v2/downloads/{id} (204).

Before, on origin/main at 85d1c16: the running ffmpeg kept going, the queued job started after it, and both finished with no download left.

17:28:34 after creating both downloads
 151873571264672395 | tracks_v1_running | progress 182.6 s
 151873582421521035 | tracks_v1_queued  |
17:29:41 about 60 s after deleting both downloads (downloads table empty)
 151873571264672395 | tracks_v1_ready | progress 870.4 s
 151873582421521035 | tracks_v1_ready | progress 766.7 s

After, on this branch, same steps and data: both jobs were retired within the delete requests, ffmpeg exited, and the .part file was removed.

17:46:01 3 s after deleting both downloads
 151875333375695303 | expired | progress 72.6 s (no ffmpeg process, artifact directory empty)
 151875333409249735 | expired |
level=INFO msg="download preparations no download needs stopped" count=1
level=WARN msg="download artifact encode aborted; lease lost or job stopped"

Neighbouring behaviour on the same build: with two devices on one job, deleting one left the encode running, and the other download became ready. Asking for the deleted file again queued the expired job, waited out the stop window (about 100 s left), and then prepared it to ready.

Risks

  • An orphaned job from another removal path, such as a profile or monitor delete, can still run for up to ten minutes after its last download goes, until its next heartbeat fails. Delete, revoke, quality changes and a late completion stop the job right away.
  • During a rolling upgrade, a replica still on the old version clears the stopped worker's lease window when it requeues a retired job, so for up to one heartbeat interval a new attempt can share the output path with the stopped encode.
  • If someone asks for a file again within two minutes of its running encode being stopped, that preparation starts up to two minutes later than before.
  • A retired job's partial encode is lost; asking for it again starts from zero.
  • Not covered: a file that active downloads still need is still rebuilt each time its storage is wiped.
  • No migration or API change.

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.1-sol (code review)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: Independent reviews of the branch diff by claude-opus-5-5 and gpt-6.1-sol, covering correctness, standards and spec. Both found that a retired running job could be queued again and claimed while its stopped worker was still writing the same output path. Fixed by keeping an unowned lease for the stop window through retirement and requeue, with a test. Also fixed: a duplicated requeue status expression, the storage architecture doc and a stale code comment. A re-review of the fix found nothing further. Accepted as is: other removal paths rely on the ten-minute sweep, and reusing an old queued job does not refresh its last-used time, so in a rare race it can be retired and then queued again, which loses partial work but not the download.

Note

Retire artifact preparations once no in-flight download needs them

  • Adds RetireAbandonedPreparations and RetireStaleAbandonedPreparations in preparation_controls.go. These expire queued or running jobs with no in-flight requester instead of deleting them, keeping the recipe and a lease window so a late link can safely requeue the job.
  • ClaimNext and Heartbeat in artifact_repo.go now skip or stop extending leases for stale abandoned jobs (10-minute grace), so workers stop work nobody needs.
  • Service.Delete, Service.RevokeDeviceDownloads, managed replacement, and completion reporting in service.go and status_events.go call the new retirement path when the last requester goes away.
  • Repository.ConfirmArtifactLink in repo.go requeues an expired artifact when a still-preparing linked download needs it, and returns a requeued flag that triggers an artifact drain.
  • Replaces the old CancelAbandonedPreparations deletion flow; removed download-triggered retirement, heartbeat fencing, and claim exclusion are covered by new database tests in preparation_controls_test.go.
  • Behavioral Change: abandoned preparations now expire rather than delete, and CancelPreparations no longer applies the abandoned-job filter; ConfirmArtifactLink returns a third requeued result, so callers must use the updated signature.

Macroscope summarized 1aa1726.

Deleting, revoking or re-qualifying the last download of a prepared file
now expires its queued or running job and stops the encode. The
preparation run also retires stale jobs no in-flight download needs, and
the claim query skips them. A create that linked a job just before it was
retired queues it again when its link is confirmed.

Refs Silo-Server#998
A retired running job keeps its id and output path. Keep an unowned lease
for the stopped worker's heartbeat window, as a pause does, and keep it
through a requeue, so a prepare-again cannot share the output path with an
encode still shutting down. Document the retirement lifecycle.
@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

This organization requires a seat for paid usage-based reviews, including automatic and on-demand reviews. Ask an admin to assign a seat or enable paid usage-based reviews for users without a seat in Billing.

Next included review available in 33 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

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: e04332b7-cb00-4280-97aa-42f2678fe8dc
Commits

Reviewing files that changed from the base of the PR and between 061bbd1 and 1aa1726.

Files selected for processing: 11

  • docs/admin-api.md
  • docs/architecture/download-storage.md
  • internal/downloads/artifact_repo.go
  • internal/downloads/artifacts.go
  • internal/downloads/preparation_controls.go
  • internal/downloads/preparation_controls_test.go
  • internal/downloads/repo.go
  • internal/downloads/service.go
  • internal/downloads/status_events.go
  • internal/downloads/storage_revoke.go
  • scripts/ci/db-contracts.txt
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@silo-triage silo-triage Bot added the size/L 200–499 added + deleted lines (all files); change volume, not priority. label Nov 13, 2026
@silo-kody

silo-kody Bot commented Nov 13, 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 ❌
⚠️ 4 Kody Rule(s) were not evaluated

These rules declare that they need repository context beyond this diff, and the review could not retrieve it, so they were not judged on this pull request:

  • Preserve optional store capabilities through production wrappers
  • Detach mandatory cleanup from request cancellation and bound its lifetime
  • Preserve durable media identity and share identity-evidence precedence
  • Bound decoder throughput trades and share direct-play eligibility

@silo-triage silo-triage Bot added bug Something isn't working priority: P2 Limited scope, workaround exists, or polish labels Nov 13, 2026
Quick104 and others added 2 commits November 14, 2026 19:19
…completion

Review fixes for retiring preparations no download needs:

- A heartbeat now fails for a job no in-flight download has needed for
  ten minutes. The preparation run that holds the sweep waits for its
  replica's running encodes, so on a single server an orphaned encode
  ran to the end.
- A late completed report retires the job as a delete does. A running
  job used to keep encoding and was killed by the sweep ten minutes
  later on a cluster only.
- Requeue moves last_used_at to now, so a file asked for again is not
  skipped by the claim query or retired before its download row lands.
- ConfirmArtifactLink locks the job FOR NO KEY UPDATE. With FOR SHARE,
  two creates confirming the same retired job deadlocked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A worker on another replica that finishes a retired job before its next
heartbeat is refused the ready transition. Its cleanup removed the file
only when the job row was gone, and retirement keeps the row, so the
whole file stayed on disk with nothing tracking it. An expired row has
no attempt writing its path, so the cleanup now removes it too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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

🤖 Claude Code (claude-opus-5-5), reviewing on behalf of a maintainer, with a cross-provider pass by Codex (gpt-6.1-sol).

The approach holds. On main, deleting the last download of a running job leaves the encode running; on this head it stops. I checked that with a test written against main, because the PR's own new tests don't compile there (the ConfirmArtifactLink signature changed).

Five findings are below, each on its line. I'm fixing all five on this branch, and each fix comes with a test that fails on this head. One more point needs a maintainer decision rather than a code change. It is on preparation_controls.go line 178.

Comment thread internal/downloads/artifacts.go Resolved
Comment thread internal/downloads/status_events.go Resolved
Comment thread internal/downloads/artifact_repo.go Resolved
Comment thread internal/downloads/repo.go Resolved
FOR UPDATE
)
UPDATE download_artifacts a SET `+expireLocatorAssignment+`, paused_at = NULL,
lease_expires_at = CASE WHEN t.running THEN now() + make_interval(secs => $2)

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.

Maintainer decision: retirement during a rolling upgrade. On main, Requeue sets lease_expires_at = NULL. Suppose a new replica retires a running job, and within the stopped worker's heartbeat window an older replica requeues it for a new download. The unowned lease is then cleared, and a worker can claim the job while the stopped encode still writes the same output path (it includes the job id). This happens only while replicas run mixed versions, and only inside a window of up to the 40-second heartbeat interval. Single-server installs are unaffected. The options are to accept it, or to release lease preservation before retirement turns on. That is a maintainer call, so I'm leaving the code as is.

@silo-triage silo-triage Bot added size/XL 500–999 added + deleted lines (all files); change volume, not priority. and removed size/L 200–499 added + deleted lines (all files); change volume, not priority. labels Nov 14, 2026
@silo-kody

silo-kody Bot commented Nov 14, 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 ❌
⚠️ 4 Kody Rule(s) were not evaluated

These rules declare that they need repository context beyond this diff, and the review could not retrieve it, so they were not judged on this pull request:

  • Preserve optional store capabilities through production wrappers
  • Detach mandatory cleanup from request cancellation and bound its lifetime
  • Preserve durable media identity and share identity-evidence precedence
  • Bound decoder throughput trades and share direct-play eligibility

@Quick104

Copy link
Copy Markdown
Contributor

🤖 Claude Code (claude-opus-5-5): review summary for head 1aa1726, with a cross-provider pass by Codex (gpt-6.1-sol).

The fix works. On the base, deleting the only download of a running job leaves the encode running. On this branch the delete stops it. I checked that with a test written against the base, because the PR's own new tests don't compile there (ConfirmArtifactLink gained a return value).

Addressed on this branch

Five findings, fixed in 4ed929f and 1aa1726. Each test below failed on 672e117 before its fix.

  • Single-server orphans: an encode on the same server whose download left by another path ran to the end, because the preparation run waits for that server's encodes. Heartbeat now fails for a job no in-flight download has needed for ten minutes. Test: TestStaleAbandonedPreparationsAreRetiredNotClaimedDB.
  • Late completed report: a running job kept encoding for nobody, then got killed ten minutes later on a cluster only. The report now retires the job as a delete does. Test: new TestLateCompletionStopsItsPreparationDB.
  • Re-asked file skipped: Requeue kept an old last_used_at, so the claim query skipped a just-requeued file until its download row landed. Requeue now sets it to now. Test: TestStaleAbandonedPreparationsAreRetiredNotClaimedDB.
  • Confirm deadlock: two creates confirming the same retired job deadlocked on FOR SHARE. The lock is now FOR NO KEY UPDATE. Reproduced with two database sessions; no Go test, because the interleaving can't be forced reliably.
  • Leaked file: a retired job's finished file stayed on disk when its worker on another replica finished before the next heartbeat. removeCanceledLocalOutput now also removes it when the row is expired. Test: TestLateCompletionStopsItsPreparationDB.

docs/architecture/download-storage.md and docs/admin-api.md describe the new stop paths. go test ./internal/downloads/... ./internal/apiv2/... passes against a freshly migrated Postgres, and make lint-changed is clean.

Left for the maintainers

  • Rolling upgrade (maintainer decision, in its thread): a replica still running main clears the stopped worker's lease window when it requeues a retired job. A new attempt can then share the output path with the stopped encode for up to one heartbeat interval. This only happens while replica versions are mixed.
  • Rare races, each bounded by the heartbeat fence or the next preparation run:
    • Delete retires the artifact it read before DeleteManaged. If a quality change lands between the read and the delete, the new job waits for the ten-minute fence.
    • The retire statement's snapshot can miss a download committed during the statement. That download then waits for the next preparation run to requeue its job.
    • DeleteUnreferencedExpired can delete a just-retired row in the moment between a create's Ensure and its insert. That download then fails with the administrator-cancel message.

Validated features

The validation board couldn't be read here; the token lacks read:project. The server downloads task #1168 shows "Not run" for C1 and C2 in its body. If C2 passed since then, it changes in a minor way: a requeued preparation can wait out a stopped worker's window. So Validation tasks: none holds as far as I can check, but it's unconfirmed.

Manual and clients

The user manual needs an update. running-a-server/download-storage.md says preparations nobody needs "are canceled" after a revoke. They are now stopped and kept for a later request. The page also doesn't say that deleting a download or changing its quality stops its preparation. I recommend a siloserver.org issue for that page.

No client shows anything new. Apple, Android, Roku and web need no change, and jellycompat has no server-prepared downloads. The evidence page still matches this head, because the fixes don't change the delete and queue behavior it shows.

Fit: 9/10 · Readiness: 8/10 — conditional (assuming CI is green)

Fit: this stops transcodes that nobody will receive, which matters most on low-power servers. It adds no setting or API surface. Readiness: the main behavior failed on the base and passes here, and each review fix has a test that failed first. The rolling-upgrade decision and the board check are still open.

@Quick104
Quick104 merged commit 3aa9506 into Silo-Server:main Nov 14, 2026
27 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 priority: P2 Limited scope, workaround exists, or polish size/XL 500–999 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] Orphaned download artifacts keep transcoding after their downloads are deleted

2 participants