You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(downloads): write a download only while its file names the download's title - #4042
Related issue: N/A
Validation tasks: none changed; the change reaches the open task #1168 (Downloads / offline — Server), whose registration cases behave the same for a file that is present and linked to the title being downloaded
#4039 keeps a renamed file's media_files row and, when the new path names another title, moves the row's offline downloads for the old title onto a missing stand-in row so they are refused and later deleted. A download registered at the same moment can miss that move. Registration resolves the file without a lock and inserts the downloads row in a later statement, and none of the four statements that write a download read or lock the file row. The retitle's single statement takes its snapshot before it waits on its row lock, so a download committed during the wait is invisible to the part that moves downloads. That download stays on the live row under the old title's ids, and serving checks only presence, library, and quality, so it keeps serving a file that now belongs to another title. Review of #4039 found this and the maintainer chose to fix it separately.
With this change a download is written only while its file is present and still linked to the title the download names.
Approach
Each of the four download-writing statements (Create and CreateBatch, CreateManagedEntriesBatch, ReplaceManagedEntry) locks the file row FOR SHARE in the statement that writes the download, and writes only when the row is not missing and its content_id/episode_id match the download's. RetitleMovedFile and ReclaimStandIn now run in a transaction that locks the row FOR UPDATE in a statement of its own before the statement that moves downloads; their existing fences are unchanged.
That gives one of two orders, from database row locks alone, so it holds across several API servers:
registration commits first: the retitle's next statement takes a fresh snapshot, sees the download, and moves it to the stand-in;
the retitle commits first: the waiting registration rereads the row, finds it no longer linked to its title, and writes nothing.
One rule covers all four statements. Single creates use the file's own links, season, series, and subscription items use the series id and the episode the file is linked to, a multi-episode file registers under its first episode, and managed entries check the entry's own ids. Extras have no download path.
A refused registration gets the same not-found answer a file that is gone gets today, on every handler that registers downloads. No API contract, migration, or settings change. An interactive managed request (a season, a series, or a single managed create) registers its entries together or not at all: one statement locks and checks every entry's file and writes none if any is refused, so a refused request holds no quota. Monitor sync keeps its partial result: it skips a refused episode and registers it on a later sync, as it does for an episode with no file. Two service paths changed to keep the not-found answer: the prepared-download create no longer falls back to replacing the entry after a refusal, and a managed batch whose row was refused returns not found.
Thirteen existing downloads tests registered downloads for files that were not linked to the titles they named (one movie file reused for every episode, fake resolvers, a schema with only a downloads table). Their fixtures now seed files linked to the titles they register; no test was removed and the fence was not loosened for them.
Validation
A database-backed test shows each of the four statements refusing a file whose link has changed. A second one drives both lock orders from two real database sessions, synchronized on pg_blocking_pids, and checks where the download ends up. Both pass repeatedly.
Two more database-backed tests cover a refused managed request writing nothing (it failed before that fix, leaving one download registered) and monitor sync skipping only the refused episode.
Without the separate lock statement the "registration holds the row" order fails with the download left on the moved row; with the title condition forced true, all four statement cases and the "retitle holds the row" order fail.
A refused interactive managed request writes nothing from its insert, but replacements of existing entries made earlier in the same request stay committed, as before this change.
ReplaceManagedEntry takes a second read to tell a refused file from a lost revision race and can misclassify if the file changes again between the reads. Either answer leaves the entry unchanged.
A refused prepared-download create can leave its encode job queued, because the job is ensured before the insert.
Writers that relink a file without a rename, such as the matcher's link writes, still do not move downloads, as on main. Registration now always checks the file's current links, but a download committed before such a relink keeps the old ids.
No deadlock was found by reading the lock order (the reclaim locks the row first, and registration takes only share locks), but it was not tested under load.
The inserts are now INSERT … SELECT … FOR SHARE, including the managed batch's join against VALUES. Plans and timing for very large managed batches were not measured.
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 says there is none.
AI Disclosure
Harness: Claude Code (in T3 Code)
Tool(s): Claude Code agent tools and a delegated agent
Model(s): claude-opus-5-5 (wrote the code), claude-fable-5-2 (direction, verification, this description)
Reject download registration for files retitled away from the download's title
Download registration is now fenced against media files that are missing or belong to another title. Service.ensureManagedDecisions uses an all-or-nothing batch insert and returns errFileNotRegistrable when an item has no row and no concurrent managed entry exists; Service.createArtifactDownload skips the managed-entry reuse fallback for that error.
RetitleMovedFile and ReclaimStandIn in file_repo_relink.go now lock the media-file row with a FOR UPDATE statement inside a transaction before moving downloads, so registration and retitle serialize correctly.
Documents the locking and snapshot ordering in missing-files.md and adds four download database contract tests to db-contracts.txt.
Test fixtures across the downloads package now seed distinct episode-linked media files instead of sharing one file.
Behavioral Change: a managed batch request that previously registered only part of its items now fails entirely with errFileNotRegistrable when an item's file has left its title; retitle failures at begin/commit now surface as errors instead of silently proceeding.
…arsed title
A file whose bytes are unchanged (same size, OSHash, and modification time)
now keeps its media_files row across any rename or move, so trickplay,
chapter images, probe data, subtitles, and downloads follow it. Before, a
rename that changed what the path parses to, such as adding a provider ID
tag, got a new row and regenerated everything.
When the new path's provider tags agree with the linked title's stored IDs,
the links stay. Otherwise the row drops its links and is matched like a new
file, and a missing stand-in row at the old path holds the old title through
the usual removal grace. Undoing such a rename gives the row its path and
links back.
Marker thumbnails no longer reset on a path change alone; the relink rewrites
their path-hashed identities.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Keep a renamed row's links only when matching the new path would resolve to
the title it already has: group and root claims, series siblings under the
observed root, then the group's provider IDs compared in the type's anchor
precedence. The comparison moves from metadata to catalog so both use it.
A stand-in reclaim that cannot be decided (database error, unreachable or
empty old root, fence lost twice) now fails the file for this scan instead of
writing it onto the stand-in.
Probe each library root once per lookup and stop once the pick is settled.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
A retitle moves the row's downloads for its old title onto the stand-in, so
they are refused and later deleted as they were with the missing row, and a
reverted rename brings them back. Without this a download kept serving a
file that now belongs to another title.
The series sibling lookup that decides whether a renamed row keeps its links
no longer counts the row itself.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
…file row
A download parked on a retitle's stand-in still pointed at the retitled row's
prepared artifact, so its remux or transcode could be served or prepared
again under the old title. Serving and preparing again now require the
artifact to belong to the download's file row.
An unlinked row that still carries downloads for a title now leaves a
stand-in for them, independent of the link comparison.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
PrepareDownloadAgain compared the artifact with the download as the caller
read it, so a download parked on a stand-in mid-request still requeued the
retitled row's artifact and became preparing. It now locks the download row
after the artifact and refuses before any requeue when the download's file
is no longer the one read or the artifact's own.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ad's title
A retitle moves a renamed file's row to another title and parks the old
title's downloads on a missing stand-in. Registration resolved the file
without a lock and inserted later, so a download written after the
retitle's statement stayed on the live row with the old title's ids.
Every statement that writes a download's media_file_id (Create,
CreateBatch, CreateManagedEntriesBatch, ReplaceManagedEntry) now locks the
file row FOR SHARE in that statement and writes only while the file is
present and linked to the download's content and episode. A refusal
answers catalog.ErrItemNotFound, the not-found a missing file gets.
The retitle and ReclaimStandIn now take the row FOR UPDATE in a statement
of their own, inside one transaction, before the statement that parks
downloads. The previous single statement took its snapshot before waiting
on the lock, so a download committed during the wait was invisible to it.
Test fixtures that registered downloads against files not linked to their
titles now seed linked files: per-episode files instead of one shared
movie file, and a media_files table in the downloads-only test schema.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Organization UI
Review profile: CHILL
Plan: Advanced
Run ID: 49e9fb96-2de5-414d-a86b-8ad778800e5c
Commits
Reviewing files that changed from the base of the PR and between dc8eba6 and 6a5c546.
Files selected for processing: 1
docs/architecture/missing-files.md
Walkthrough
The scanner adds moved-file relinking, retitling, and stand-in reclaim operations. Download registration now checks file presence and title links while locking the file row. Managed batch requests reject unregistrable files without partial writes.
Changes: Moved-File Relinking and Download Fencing
Layer / File(s)
Summary
Add relink, retitle, and stand-in operations internal/scanner/file_repo_relink.go
The repository adds fenced relinking, retitling, and stand-in reclaim operations. It updates file and download links and adjusts marker thumbnail identities when paths change.
Fence download registration against file changes internal/downloads/registration_fence.go, internal/downloads/repo.go, internal/downloads/service.go, docs/architecture/missing-files.md
Registration checks that the media file is present and linked to the requested content and episode. Managed batch creation uses all-or-nothing registration, and failed ownership checks do not enter concurrent-entry recovery. The architecture document describes the row-lock ordering.
Test registration fences and file-specific fixtures internal/downloads/*_test.go, scripts/ci/db-contracts.txt
Database tests cover refused registrations, managed batches, monitor sync, and registration-versus-retitle serialization. Test fixtures now seed media-file rows and use file-specific content and episode identifiers.
sequenceDiagram
participant DownloadService
participant DownloadRepository
participant PostgreSQL
participant ScannerFileRepository
DownloadService->>DownloadRepository: Create download
DownloadRepository->>PostgreSQL: Validate file links and lock FOR SHARE
PostgreSQL-->>DownloadRepository: Insert or refuse registration
ScannerFileRepository->>PostgreSQL: Lock file FOR UPDATE and move title links
PostgreSQL->>PostgreSQL: Move old-title downloads to stand-in
Loading
Possibly related PRs
Silo-Server/silo-server#4039: Adds the retitle and stand-in reclaim operations that this PR uses and coordinates with through row locking.
Silo-Server/silo-server#2877: Adds the moved-file candidate and relink operations that this PR extends with retitling and stand-in reclaim.
Suggested reviewers:rhainland, blurbery
Merge Risk: Moderate · previous review dc8eb
A refused managed request can still change existing downloads, and overlapping scanner work can leave title associations incorrect. Resolve those risks before merging unless their impact is explicitly accepted.
Security architecture risk: Low · up to dc8eb
The change strengthens download authorization during file retitles. The reviewed flows retain ownership checks and refuse stale file identities. Remaining uncertainty concerns deployment compatibility and concurrency behavior beyond the inspected cases, rather than an established new security weakness.
Retained concerns
No architecture-level concerns identified.
Security review details
Security Blast Radius
inferred — The relevant exposure is title-authorized downloads following a shared media-file identifier after that file changes title. A transition can affect downloads belonging to multiple users that reference the same file row. The inspected changes constrain that relationship; they do not establish broader tenant, credential, or infrastructure authority changes.
Trust Boundaries and Controls
observed — Authorization-sensitive file identity is rechecked in the database statement that writes the download, not solely in an earlier application lookup. Replacement's later read only classifies a failed update; it cannot authorize another write. Refusal is also excluded from the single-artifact creation fallback that otherwise reuses or replaces a concurrent managed entry.
Resilience and Maintainability Implications
observed — Retitle and reclaim defer rollback independently of request cancellation. The concurrency test explicitly exercises registration-first and retitle-first ordering, asserting respectively that the download moves to the stand-in or that late registration writes nothing. These are inspected test assertions, not execution results; broader contention and recovery behavior remain unverified.
Hardening Proposals
proposed — Document the compatible-version rollout and rollback boundary and verify the production transaction-isolation assumption before treating the race protection as effective across all registration and scanner instances.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the main change: downloads are written only while the file still names the download's title. It matches the registration fence in registration_fence.go and the related repo, service, a…
Description check
The description states the problem, approach, validation, risks, and AI disclosure. It explains the four download-writing statements, the FOR SHARE and FOR UPDATE locking, the all-or-nothing managed b…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Full details: Title check
Explanation
The title names the main change: downloads are written only while the file still names the download's title. It matches the registration fence in registration_fence.go and the related repo, service, and test changes. The title uses the fix() prefix and stays under one sentence, though it is 79 characters, which is at the long end.
Full details: Description check
Explanation
The description states the problem, approach, validation, risks, and AI disclosure. It explains the four download-writing statements, the FOR SHARE and FOR UPDATE locking, the all-or-nothing managed batch change, and the updated test fixtures. These match the raw summary's registration_fence.go, repo.go, service.go, and retitle/reclaim changes.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
repo.go grew past the size ratchet's 1000-line limit. Move the
registration fence into registration_fence.go: the file-lock condition,
errFileNotRegistrable, the fenced insert SQL and its column and cast
helpers, downloadInsertArgs, and the four statements that write a
download's file (Create, CreateBatch, CreateManagedEntriesBatch,
ReplaceManagedEntry). The SQL and signatures are unchanged.
ReplaceManagedEntry's error handling now returns early instead of nesting,
which changed-lines lint flags once the function is in a new file. It takes
the same branches and returns the same errors.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Base automatically changed from
fix/scanner-reuse-artifacts-on-rename to
mainNovember 13, 2026 00:41
silo-triageBot
added
size/XXXL
3000+ added + deleted lines (all files); change volume, not priority.
and removed
size/XL
500–999 added + deleted lines (all files); change volume, not priority.
labels
Nov 13, 2026
At this call, no download with ID "parked" exists. PrepareDownloadAgain therefore returns ErrDownloadNotActive for the missing row, even if its stored-file mismatch check is broken. Insert a parked download row before this assertion. Keep the later stale-caller assertion as a separate case.
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: c5a75df9-d18f-41b7-97bd-5179bfd99b1c
Commits
Reviewing files that changed from the base of the PR and between b809071 and db0410a.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
⚠️ Outside diff range comments (4)
Major · Stop reclamation when the origin has no configured root. · file_relink.go:196-197
internal/scanner/file_relink.go:196-197 Major · Data Integrity & Integration · Quick win
Stop reclamation when the origin has no configured root.
After a retitle across two library roots, remove the destination root and move the file back. The origin can still appear in MovedFileCandidates, but this branch discards it without probing its path. Root replacement does not itself remove those file rows. (raw.githubusercontent.com)
The later i < 0 branch returns false, nil. processFile then reaches its ordinary upsert at internal/scanner/scanner.go, Line 3177. That upsert clears stand_in_for_file_id, leaving the original row's artifacts behind instead of preserving recovery. (raw.githubusercontent.com)
When this candidate is standIn.forFileID, return errStandInUndecided instead of dropping it.
Based on learnings, an undecided reclaim must stop instead of overwriting the stand-in and clearing its reference.
Source: Learnings
Major · Fence the episode-link write on the title the matcher read. · file_repo_relink.go:292-293
internal/scanner/file_repo_relink.go:292-293 Major · Data Integrity & Integration · Heavy lift
Fence the episode-link write on the title the matcher read.
The matcher reads unlinked files, then calls UpdateEpisodeLink by file ID. That method locks the row but does not check its current title. If the file is retitled between the read and the write, the stale write sets an episode from the previous title on the retitled row.
The fix needs the title the matcher used. Pass that series identity into UpdateEpisodeLink. Add it to the UPDATE predicate, and have the function return a stale result when no row matches. Update the EpisodeLinker interface and its callers. The exact signature change needs review across the matcher and its test fakes, so this comment does not include a diff.
Source: Learnings
Minor · Use a live context for fixture cleanup. · file_relink_db_test.go:404
internal/scanner/file_relink_db_test.go:404 Minor · Functional Correctness · Quick win
Use a live context for fixture cleanup.
Go 1.26.4 cancels t.Context() before cleanup callbacks run. This callback therefore passes an already-canceled context to pool.Exec. The pool rejects acquisition before executing the DELETE, and the ignored error hides the failed fixture cleanup. (pkg.go.dev)
Use a separate bounded context and report cleanup errors.
Proposed change
- t.Cleanup(func() { _, _ = pool.Exec(ctx, `DELETE FROM media_items WHERE content_id = $1`, contentID) })+ t.Cleanup(func() {+ cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ if _, err := pool.Exec(cleanupCtx, `DELETE FROM media_items WHERE content_id = $1`, contentID); err != nil {+ t.Errorf("clean up seeded item: %v", err)+ }+ })
Minor · Reconcile the old title's memberships after a retitle. · file_repo_relink.go:324
internal/scanner/file_repo_relink.go:324 Minor · Data Integrity & Integration · Heavy lift
Reconcile the old title's memberships after a retitle.
When ScanFile retitles a file, RetitleMovedFile leaves a missing stand-in at the old path. The stand-in keeps the old title's content_id (file_repo_relink.go:317-318, 324). The regular-file branch of ScanFile does not call any membership reconciliation helper (scanner.go:2638-2821). The old title's item membership therefore stays until a folder-wide reconciliation runs.
The stand-in is created on any retitle whose old links differ, not only on the last file of a title. The stale membership matters only when no other present file remains for the old title.
Consider reconciling the old title's links at the end of the retitle path. The scoped reconciliation that already handles extra-file moves (reconcileScopedLibraryMemberships, scanner.go:2737) is one option to reuse.
At this call, no download with ID "parked" exists. PrepareDownloadAgain therefore returns ErrDownloadNotActive for the missing row, even if its stored-file mismatch check is broken. Insert a parked download row before this assertion. Keep the later stale-caller assertion as a separate case.
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: c5a75df9-d18f-41b7-97bd-5179bfd99b1c
Commits
Reviewing files that changed from the base of the PR and between b809071 and db0410a.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.
On the four outside-diff comments and the nitpick in the latest CodeRabbit review: they are about code that merged with #4039 and is on main now, not about this PR's diff, so they are not changed here. The episode-link fence is #4041. The other three (reclaim when the origin path has no configured root, membership reconciliation after a retitle, and the two test-fixture points) are noted for the maintainer to triage separately.
…at all
When one file of a managed season or series request had left its title,
the fenced batch insert wrote the request's other entries and skipped the
refused one, and the request then failed. The client got an error while
entries it never saw stayed registered and counted toward its quota.
Interactive managed requests now use CreateManagedEntriesAllOrNothing:
one statement locks and checks every entry's file and inserts none of them
when any is refused, as the batch insert wrote nothing when a file was
deleted under it. The request answers the missing-file not-found.
A monitor sync keeps the partial result: it skips an episode whose file
left its title and registers it on a later sync, as it does an episode
with no file. An ephemeral season batch already rolled back as a whole.
Point the architecture doc at registration_fence.go, where the fenced
statements now live.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 settingsReview 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
Files skipped from review as they are similar to previous changes: 1
docs/architecture/missing-files.md
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Major · Data Integrity & Integration · Heavy lift
Include existing-entry updates in the all-or-nothing request.
If a managed batch updates an existing episode and a new episode’s file has left its title, replace runs at Line 984 or Line 1029 before this insert. The insert writes nothing, and the fallback returns errFileNotRegistrable. The existing entry’s batch ID or revision can remain changed despite the failed request. WithUserQuotaLock does not roll back those writes. Put replacements and inserts in one rollback-capable transaction. The documented batch contract says a refused request writes none of its downloads. (raw.githubusercontent.com)
The reason will be displayed to describe this comment to others. Learn more.
Not changed here. The ordering this describes is on main already: a managed request replaces existing entries and then inserts new ones in separate statements, so a replacement made earlier stays whenever the insert fails, for any reason; the fence adds one more way for the insert to refuse. Putting replacements and inserts in one transaction changes how the quota lock and the repository calls compose, so it is left for the maintainer to take separately. The doc sentence that overstated the contract is corrected in the latest commit, and the PR's Risks section names what a refused request leaves in place.
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 settingsReview 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
Merge origin/main and rework the fix to fit its registration fence
(Silo-Server#4042), which refuses a download whose file is not linked to the row's
episode. A multi-episode file is linked to its first episode, so it can
only be registered there.
Season picking now prefers an episode's own files over a multi-episode
file linked to an earlier episode. An episode whose only file is that
range is served through the first episode's entry when the first episode
picks it too, and is skipped as multi_episode_conflict when it keeps a
different file. The single-download path goes back to main's keying.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bugSomething isn't workinggoPull requests that update go codeimpact: playbackCan't play, stalls, or wrong mediapriority: P2Limited scope, workaround exists, or polishsize/XXL1000–2999 added + deleted lines (all files); change volume, not priority.stackedBase is another open PR; merge in stack order named in the body
1 participant
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Related issue: N/A
Validation tasks: none changed; the change reaches the open task #1168 (Downloads / offline — Server), whose registration cases behave the same for a file that is present and linked to the title being downloaded
#4039 keeps a renamed file's
media_filesrow and, when the new path names another title, moves the row's offline downloads for the old title onto a missing stand-in row so they are refused and later deleted. A download registered at the same moment can miss that move. Registration resolves the file without a lock and inserts thedownloadsrow in a later statement, and none of the four statements that write a download read or lock the file row. The retitle's single statement takes its snapshot before it waits on its row lock, so a download committed during the wait is invisible to the part that moves downloads. That download stays on the live row under the old title's ids, and serving checks only presence, library, and quality, so it keeps serving a file that now belongs to another title. Review of #4039 found this and the maintainer chose to fix it separately.With this change a download is written only while its file is present and still linked to the title the download names.
Approach
Each of the four download-writing statements (
CreateandCreateBatch,CreateManagedEntriesBatch,ReplaceManagedEntry) locks the file rowFOR SHAREin the statement that writes the download, and writes only when the row is not missing and itscontent_id/episode_idmatch the download's.RetitleMovedFileandReclaimStandInnow run in a transaction that locks the rowFOR UPDATEin a statement of its own before the statement that moves downloads; their existing fences are unchanged.That gives one of two orders, from database row locks alone, so it holds across several API servers:
One rule covers all four statements. Single creates use the file's own links, season, series, and subscription items use the series id and the episode the file is linked to, a multi-episode file registers under its first episode, and managed entries check the entry's own ids. Extras have no download path.
A refused registration gets the same not-found answer a file that is gone gets today, on every handler that registers downloads. No API contract, migration, or settings change. An interactive managed request (a season, a series, or a single managed create) registers its entries together or not at all: one statement locks and checks every entry's file and writes none if any is refused, so a refused request holds no quota. Monitor sync keeps its partial result: it skips a refused episode and registers it on a later sync, as it does for an episode with no file. Two service paths changed to keep the not-found answer: the prepared-download create no longer falls back to replacing the entry after a refusal, and a managed batch whose row was refused returns not found.
Thirteen existing downloads tests registered downloads for files that were not linked to the titles they named (one movie file reused for every episode, fake resolvers, a schema with only a
downloadstable). Their fixtures now seed files linked to the titles they register; no test was removed and the fence was not loosened for them.Validation
pg_blocking_pids, and checks where the download ends up. Both pass repeatedly.go build ./...,gofmt,go veton the touched packages,make lint-changedagainst the fix(scanner): keep a renamed file's row when the rename changes its parsed title #4039 head, andmake verify-local-paths: pass./api/v2tests against a migrated Postgres pass, and the rename test from fix(scanner): keep a renamed file's row when the rename changes its parsed title #4039 passes.make test-db-pinsrunner; CI covers them.Evidence
No user-visible change. The page holds the steps, the build, and the test results.
Evidence: https://evidence.siloserver.org/r/silo-server/pr-4042/
Risks
ReplaceManagedEntrytakes a second read to tell a refused file from a lost revision race and can misclassify if the file changes again between the reads. Either answer leaves the entry unchanged.main. Registration now always checks the file's current links, but a download committed before such a relink keeps the old ids.INSERT … SELECT … FOR SHARE, including the managed batch's join againstVALUES. Plans and timing for very large managed batches were not measured.Checklist
AI Disclosure
🤖 Generated with Claude Code
Note
Reject download registration for files retitled away from the download's title
Service.ensureManagedDecisionsuses an all-or-nothing batch insert and returnserrFileNotRegistrablewhen an item has no row and no concurrent managed entry exists;Service.createArtifactDownloadskips the managed-entry reuse fallback for that error.RetitleMovedFileandReclaimStandInin file_repo_relink.go now lock the media-file row with aFOR UPDATEstatement inside a transaction before moving downloads, so registration and retitle serialize correctly.errFileNotRegistrablewhen an item's file has left its title; retitle failures at begin/commit now surface as errors instead of silently proceeding.Macroscope summarized 6a5c546.