Skip to content

fix(downloads): pick the version the profile watches when none is named - #1630

Merged
Quick104 merged 3 commits into
Silo-Server:mainfrom
Rhainland:fix/download-version-preference
Sep 28, 2026
Merged

Quick104 merged 3 commits into
Silo-Server:mainfrom
Rhainland:fix/download-version-preference

Conversation

@Rhainland

@Rhainland Rhainland commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #1167
Validation tasks: changes #1168 C1 (not yet run; automatic picks now respect library access and the quality ceiling)

When a download request has no media_file_id, the server saves the highest-resolution file and breaks ties by database order. That covers season and series downloads, monitored series, and any client that leaves Auto to the server. A user who watches a different version, for example a 720p file with an English sidecar .srt next to a 1080p file without one, gets the 1080p file offline and loses the subtitles.

Approach

Native v2 requests now pick from the profile's watch history, in this order:

  1. The file the profile last played for that movie or episode.
  2. For an episode, the version closest to the series' most recent play, matched on edition, then resolution, HDR and video codec. The lookup reads only the requested episodes plus the profile's latest 200 progress rows, so each season page costs the same regardless of series length.
  3. The highest resolution, with the lowest file id breaking ties.

The frozen v1 bridge keeps the highest-resolution default for single, series and monitor requests, so a repeated v1 series request never swaps files a device already has. v2 season pages already keep existing entries unless the client guards them, and monitors only add entries, so a change in watch history never replaces downloaded episodes. Only versions the profile may play (library access and quality ceiling) are candidates for an automatic pick. Requests with media_file_id behave as before, and items with one file skip the history reads. docs/downloads-api.md documents the order.

The clients now send the version they show: Silo-Server/silo-apple#536. Android also needed Silo-Server/silo-android#407, because episode downloads were rejected with 404, and Silo-Server/silo-android#408.

Validation

  • Go build, gofmt, go vet, make lint-changed (0 issues) and every verify target in the gate pass.
  • internal/downloads against a migrated Postgres test database passes with no skips. New tests cover the three rules, the v1 opt-out for single and monitor requests, and the bounded history read.
  • make test-go fails only in tests this branch does not touch, and they fail the same way on unmodified main on the macOS machine used: TestAdminResourceCapabilitiesAndScope (expects Linux cgroups) and the internal/playback hardware-probe tests. Three internal/jellycompat transcode-timing tests failed under full-suite load and pass when run alone.
  • Web gate: install, lint, format, build and budget pass. make test-web fails on this machine's Node v25 (localStorage.clear is not a function from jsdom); the branch has no web/ changes.
  • Manual, on a local server built from this branch with a two-episode series where each episode has a 720p file with an English .srt and a 1080p file: after E1 was played in 720p, a v2 season download registered 720p for both episodes (1080p before). With no history it registered 1080p, and the same request through v1 still registered 1080p. Repeating a season request after the history moved to 1080p kept the existing entries.

Risks

v2 clients that omit media_file_id can now get a different file than before; the docs describe the order. Each download that needs a choice adds one bounded progress read (200 rows) and one file lookup, and a failed read falls back to the old default.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.

AI Disclosure

  • Harness: Claude Code (Claude Agent SDK) in T3 Code
  • Tool(s): Claude Code; OpenAI Codex CLI 0.155.1 (codex review --uncommitted) for independent review
  • Model(s): claude-opus-5-5 (Claude Opus 5.5, 1M context); gpt-6-astra (Codex, medium reasoning effort)
  • Involvement: AI-assisted. Code and tests were written by claude-opus-5-5; the submitter reviewed the complete diff and validated the changes end to end.
  • Adversarial review: A Claude Code review (medium) and Codex (gpt-6-astra, medium) read the full diff. Fixed: monitor sync through v1 followed watch history (v1 now keeps the highest-resolution default), and every season or monitor page re-read the whole series' history (now bounded to the requested episodes plus 200 recent rows). Declined after testing: a reported swap of already-downloaded episodes on a repeated v2 season request; v2 pages keep unguarded entries, confirmed on a local server. Codex re-reviewed the fixes and found nothing further.

Note

Use profile watch history to pick download versions when no media_file_id is given

  • When a download request omits media_file_id, the service now picks the version the requesting profile last watched: the item's last-played file first, then the best match for recent series history (edition, resolution, HDR, codec), then the old default ordering
  • Series, season, and subscription downloads resolve each episode the same way, and automatic picks are filtered by the profile's catalog access permissions
  • History is best-effort: if the progress store is missing or fails to read, selection falls back to the default; series matching looks at the latest 200 progress entries
  • Replaces the old pickBestFile highest-resolution selector with versionPreference.pick and preferredByDefault in version_preference.go; see also service.go and download_create.go
  • Behavioral Change: automatic (no media_file_id) download version selection can now return a lower-resolution file than before when history points there; explicit file IDs are unchanged, and legacy subscription sync keeps the old behavior

Macroscope summarized f077ae8.

A download that omits media_file_id (season, series and monitored
episodes, and any client that leaves Auto to the server) always got the
highest-resolution file, with ties going to database order. A user who
watches a different version, such as a 1080p file with a sidecar .srt
next to a 2160p file without one, got the other file offline.

Native requests now pick from the profile's watch history: the file last
played for that movie or episode, then for an episode the version closest
to the series' most recent play (edition, resolution, HDR, video codec)
within the profile's latest 200 progress rows, then the highest
resolution with the lowest file id breaking ties. The v1 bridge keeps its
highest-resolution default, so a repeated v1 request never swaps files a
device already has. Items with one file skip the history reads.
@kody-ai

kody-ai Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the `@kody start-review` command at the root of your PR.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Providing Context (Files & MCPs)

Add these hints in your PR description (or a comment) to unlock deeper checks:

  • Ticket / Acceptance Criteria: `Refs: ABC-123` (Linear/Jira/Asana/ClickUp/Trello) or a direct ticket link.
  • Bugfix Validation: a Sentry/Datadog/Bugsnag event link (or paste the stack trace/error message).
  • Endpoint Risk: mention the route (e.g., `POST /api/payments`) or controller/action name.
  • Attach a repo file as context: use an explicit marker like `@file:docs/guide.mdx#L10-L50` (replace with your real path).
  • API Contract Docs: include `@file:openapi.yaml` or `@file:swagger.json` when changing routes/schemas.
  • Definition of Done / Standards: include `@file:DOD.md` or `@file:CONTRIBUTING.md` if your repo has them.
  • Design System Source of Truth: include `@file:ui/index.ts` (replace with your DS entrypoint path).
  • Feature Flags: include the flag key/name and `@file:flags.ts` / `@file:config.json` (and optionally the PostHog flag name).
  • Edge/CDN Rules: link the Cloudflare rule/zone or describe the intended redirect/header behavior.
  • Attach an MCP tool output: use `@mcp<provider|tool>` (replace with an installed MCP provider + tool, e.g., `@mcp<sentry|events.search>`).
Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Access your configuration settings here.

@coderabbitai

coderabbitai Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Warning

Review limit reached

Next included review available in 33 minutes.

Check out review usage here.

View limit details

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

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: e0c8c0b3-ae37-49e3-9435-2032bce29a82

📥 Commits

Reviewing files that changed from the base of the PR and between 6e5412e and f077ae8.

📒 Files selected for processing (8)
  • docs/downloads-api.md
  • internal/downloads/file_lookup_test.go
  • internal/downloads/service.go
  • internal/downloads/subscription_exclusion_test.go
  • internal/downloads/subscription_service.go
  • internal/downloads/subscription_sync_page.go
  • internal/downloads/version_preference.go
  • internal/downloads/version_preference_test.go

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: b6474d26-4444-4f9d-a8f0-5c57fc8023d1

📥 Commits

Reviewing files that changed from the base of the PR and between ad899be and 6e5412e.

📒 Files selected for processing (9)
  • docs/downloads-api.md
  • internal/apiv2/download_create.go
  • internal/downloads/file_lookup_test.go
  • internal/downloads/service.go
  • internal/downloads/subscription_exclusion_test.go
  • internal/downloads/subscription_service.go
  • internal/downloads/subscription_sync_page.go
  • internal/downloads/version_preference.go
  • internal/downloads/version_preference_test.go

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


📝 Walkthrough

Walkthrough

Download file selection can use profile watch history. Native requests and paged subscription sync pass profile context for selection; regular subscription sync retains the default behavior. The API documentation describes how the server selects a version when media_file_id is omitted.

Changes

Download version history

Layer / File(s) Summary
Load and apply version preferences
internal/downloads/version_preference.go, internal/downloads/version_preference_test.go
The new preference logic uses item progress and recent series history to select files. It scores edition, resolution, HDR, and video codec, then uses quality and file ID for ordering. Tests cover preference selection and fallback behavior.
Enable history-based download selection
internal/downloads/service.go, internal/apiv2/download_create.go, docs/downloads-api.md, internal/downloads/file_lookup_test.go
Download creation and episode selection pass user and profile context to file resolution. The API request enables VersionFromHistory. Documentation describes selection when media_file_id is omitted. Tests cover request resolution and episode-page selection.
Select versions for subscription sync
internal/downloads/subscription_service.go, internal/downloads/subscription_sync_page.go, internal/downloads/subscription_exclusion_test.go, internal/downloads/version_preference_test.go
Paged subscription sync enables history-based selection. Regular subscription sync passes an empty profile ID. Tests cover both selection paths.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant DownloadClient
  participant Registry
  participant DownloadsService
  participant ProgressStore
  participant FileRepository
  DownloadClient->>Registry: Submit download request
  Registry->>DownloadsService: Create with VersionFromHistory enabled
  DownloadsService->>ProgressStore: Load profile progress and recent history
  ProgressStore-->>DownloadsService: Return progress rows
  DownloadsService->>FileRepository: Resolve episode files for history rows
  FileRepository-->>DownloadsService: Return episode files
  DownloadsService->>DownloadsService: Select preferred file
Loading

Suggested reviewers: quick104

Merge Risk: 🟡 Moderate · up to 6e541

Some downloads can appear ready but fail whenever requested. Align file selection with the serving access rules before merging.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 6e541

A download can now be registered for a previously watched version that the user is no longer allowed to retrieve. File delivery still blocks access, but the affected download may appear ready and remain unusable. The impact is limited to affected users and entries; no unauthorized file delivery was established.

Retained concerns

  • Medium · security · inferred: History-based selection can register a file that passes item-level admission but fails the file-level access check when its bytes are requested. An additive page or subscription replay will not automatically replace that entry after the preferred version changes.
Security review details

Security Blast Radius

  • inferred — The identified impact is an authenticated user’s affected download entries and offline availability, including entries on that user’s managed device. Candidate-file matching and delivery-time checks do not support a claim of cross-user history access or unauthorized byte delivery.

Security Findings and Attack Paths

  • inferred — If the profile’s last-played file is no longer permitted but another file for the item is permitted, an omitted-ID request can persist the forbidden selection. Serving rejects it; an existing additive page or subscription entry is not automatically reconsidered. The underlying explicit-ID admission mismatch predates this change.

Trust Boundaries and Controls

  • observed — The native API derives viewer identity, progress reads use a store opened for that user and queried for the profile, and a historical file ID must match a file resolved for the requested item. These controls constrain history’s influence on selection; they do not validate current file-level access before registration.

Resilience and Maintainability Implications

  • observed — History lookup errors fall back to default selection. Paged subscription registration rechecks active subscription state under a lock and inserts only absent managed identities, containing duplicate-registration and retry effects but also leaving an unusable existing selection unchanged.

Hardening Proposals

  • proposed — Apply the effective file-level access policy to candidate selection or before registering a selected file, while retaining delivery-time rechecks for access changes after registration.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 8 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: selecting the profile-watched version when no media file is specified.
Description check ✅ Passed The description directly explains the problem, implementation, compatibility behavior, validation, and risks related to the download version-selection changes.
Full details: Docstring Coverage

Explanation

Docstring coverage is 26.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 8 files. (1 skipped: 1 unsupported.)

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Comment thread internal/apiv2/download_create.go Resolved
An automatic pick could register a version the profile's library access
or quality ceiling forbids, leaving an entry that looks ready but can
never be served. Candidates are now narrowed with the request's access
filter first; when none qualify the full list is kept and serving reports
the refusal as before.
@kody-ai

kody-ai Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the `@kody start-review` command at the root of your PR.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Providing Context (Files & MCPs)

Add these hints in your PR description (or a comment) to unlock deeper checks:

  • Ticket / Acceptance Criteria: `Refs: ABC-123` (Linear/Jira/Asana/ClickUp/Trello) or a direct ticket link.
  • Bugfix Validation: a Sentry/Datadog/Bugsnag event link (or paste the stack trace/error message).
  • Endpoint Risk: mention the route (e.g., `POST /api/payments`) or controller/action name.
  • Attach a repo file as context: use an explicit marker like `@file:docs/guide.mdx#L10-L50` (replace with your real path).
  • API Contract Docs: include `@file:openapi.yaml` or `@file:swagger.json` when changing routes/schemas.
  • Definition of Done / Standards: include `@file:DOD.md` or `@file:CONTRIBUTING.md` if your repo has them.
  • Design System Source of Truth: include `@file:ui/index.ts` (replace with your DS entrypoint path).
  • Feature Flags: include the flag key/name and `@file:flags.ts` / `@file:config.json` (and optionally the PostHog flag name).
  • Edge/CDN Rules: link the Cloudflare rule/zone or describe the intended redirect/header behavior.
  • Attach an MCP tool output: use `@mcp<provider|tool>` (replace with an installed MCP provider + tool, e.g., `@mcp<sentry|events.search>`).
Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Access your configuration settings here.

@macroscopeapp

macroscopeapp Bot commented Sep 28, 2026

Copy link
Copy Markdown

Validation impact: silo-server#1168 C1 is affected, not unaffected. The native POST /api/v2/downloads handler passes the profile access filter to Create and CreateSeriesPage; the diff then filters automatic file candidates by library access and quality ceiling before registration. This changes the actual-request permission path C1 covers; quota and bandwidth enforcement are unchanged. C1 is currently Not run, so there is no prior result to re-check; it needs its first run after merge. C2 and the iOS/Android Downloads cases are also Not run.

Please update the line so it does not describe C1 as unaffected.

Suggested line:
Validation tasks: changes #1168 C1

Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed.

Posted via Macroscope — v1 validation impact

Comment thread docs/downloads-api.md Resolved
An automatic pick narrows candidates to versions the profile may play but
keeps all of them when none qualify, so the create or the later file
request can still be refused. The doc claimed that could not happen.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@kody-ai

kody-ai Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the `@kody start-review` command at the root of your PR.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Providing Context (Files & MCPs)

Add these hints in your PR description (or a comment) to unlock deeper checks:

  • Ticket / Acceptance Criteria: `Refs: ABC-123` (Linear/Jira/Asana/ClickUp/Trello) or a direct ticket link.
  • Bugfix Validation: a Sentry/Datadog/Bugsnag event link (or paste the stack trace/error message).
  • Endpoint Risk: mention the route (e.g., `POST /api/payments`) or controller/action name.
  • Attach a repo file as context: use an explicit marker like `@file:docs/guide.mdx#L10-L50` (replace with your real path).
  • API Contract Docs: include `@file:openapi.yaml` or `@file:swagger.json` when changing routes/schemas.
  • Definition of Done / Standards: include `@file:DOD.md` or `@file:CONTRIBUTING.md` if your repo has them.
  • Design System Source of Truth: include `@file:ui/index.ts` (replace with your DS entrypoint path).
  • Feature Flags: include the flag key/name and `@file:flags.ts` / `@file:config.json` (and optionally the PostHog flag name).
  • Edge/CDN Rules: link the Cloudflare rule/zone or describe the intended redirect/header behavior.
  • Attach an MCP tool output: use `@mcp<provider|tool>` (replace with an installed MCP provider + tool, e.g., `@mcp<sentry|events.search>`).
Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Access your configuration settings here.

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

Review summary

Reviewed head: f077ae8

Addressed

  • Doc overclaim (low, docs only): docs/downloads-api.md said an automatic pick never registers a file the server would refuse to serve. When none of an item's versions pass the access filter, allowedCandidates keeps all of them, so a series or season page at original can still register a file that serving refuses. f077ae8 describes the fallback and leaves the behavior as it is. The fallback lets a quality preset transcode an over-ceiling source.
  • Kody's access finding: checked 1626a35. resolveFile and episodeItemsWithSkipped both filter candidates before picking.

Checked, no defect found

  • A repeated v2 request without media_file_id can't swap a downloaded file. Managed single downloads require expected_revision, season pages keep unguarded existing entries, and monitor sync only inserts absent entries.
  • v1 keeps highest resolution. The file lookups already order by id ASC, so the new lowest-id tie-break matches the old pick and v1 devices see no swap.
  • Missing files are excluded at the query. Progress hints are copied from the source file's fields, so the resolution, HDR, codec and edition comparisons use the same format. The history read is one top-200 page per request.

Validated features: none affected. Every case on #1168, Silo-Server/silo-apple#319 and Silo-Server/silo-android#329 is still "Not run", and the PR's Validation tasks: line is accurate.

Validation: internal/downloads and internal/apiv2 pass against a freshly migrated Postgres with no DB skips; gofmt and go vet are clean. All CI checks pass on this head. Go test first failed in TestFailedBackendIsReplaced (internal/librarymonitor, a 10 s timing test outside this diff) and passed on re-run.

Mergeability: 9/10, ready. The server picks a version only when the client names none, the order is documented, and the frozen v1 bridge keeps its old default. No open findings remain.

AI-assisted review: Claude Code with claude-opus-5-5.

@Quick104
Quick104 merged commit 64be2bf into Silo-Server:main Sep 28, 2026
27 of 28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants