Skip to content

feat(downloads): offline sync for mobile — downloads v2 - #258

Merged
Quick104 merged 21 commits into
mainfrom
feat/downloads-v2-offline-sync
Jul 2, 2026
Merged

Quick104 merged 21 commits into
mainfrom
feat/downloads-v2-offline-sync

Conversation

@Quick104

@Quick104 Quick104 commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Mobile clients (Android, Apple) need fully offline playback with watch state that stays consistent across reconnects. Silo's v1 downloads were ephemeral web-only records with no device awareness, no offline bundle, and no way to reconcile progress recorded while offline.

What this adds

Downloads V2 per docs/superpowers/specs/2026-06-18-offline-sync-mobile-design.md:

  • Device-scoped download registry — one reshaped downloads table carrying both ephemeral web rows (device_id IS NULL) and managed device-library entries, authorized on (user, profile, header device) with pre-serve content-access re-checks.
  • Offline playback manifest — a stable, presigned-URL-free bundle (metadata, subtitle/artwork proxy refs, chapters, markers, integrity metadata), single and per-batch.
  • Offline progress reconciliation — LWW on a server-clamped event_at with a trigger-stamped synced_seq cursor for ?since= deltas; client clocks can never poison cursors.
  • Quality ladder + prepare-to-file pipeline — admin-gated transcode/remux to a single seekable file through a leased, attempt-counted, crash-recoverable artifact queue with dedup and LRU byte-budget cleanup.
  • Series/season downloads + client-pull monitoring — batch registration and device-scoped subscriptions synced on app open; no server-side worker.
  • Client contract in docs/downloads-api.md, including Apple (§10) and Android (§11) handoff guides and a capability endpoint for feature detection.

Review hardening (second half of the branch)

A full adversarial review of the feature produced 13 remediation commits (eea4366e..b3c20d93), all landed here: sqlite-userdb-backend support for managed downloads (FK drop + app-level profile purge), async encode kick (a bitrate POST could previously block on the whole ffmpeg queue), quota enforced before encode enqueue with preparing counted, ephemeral artifact links protected from LRU eviction, per-item batch-manifest skips, season 0 (Specials), always-array quality_presets, subscription fixes (paused-sync gate, calendar-day future mode, batched registration with an honest registered count), trigger-owned event_at (stale-progress resurrection fix), migration squash + working Down, age-based artifact/ephemeral hygiene sweeps, and a consolidation pass (shared ffmpeg filter args, one threshold-rule home, dead code removal).

Scope / API rules

  • Pre-lock reshape: the existing /api/v1/downloads contract is intentionally reshaped, not extended — the only shipped consumer is the first-party web app, updated in lockstep here. The spec documents this divergence from the additive-only rule; it lands before scope lock and before any mobile client ships.
  • Scope gate: the v1 capability-proposal issue for offline sync has not been filed yet — this PR needs its Part of #NNN once that issue exists. Flagging rather than hiding it.
  • The follow-up download limits & restrictions design (quality ceiling, batch cap, per-user overrides) is included as a draft spec; this PR deliberately does not implement it.

Deployment notes

  • Branch/dev databases that applied the deleted corrective migration need: DELETE FROM goose_db_version WHERE version_id = 20260621020459;
  • Includes the fresh-install fix for migration 20260618164519 (goose StatementBegin/End around a DO $$ block); identical to the fix landing on main, merges cleanly.
  • New settings: none required; transcode remains off by default (download.transcode_enabled + per-user flag).

Risks & follow-ups

  • /direct-download still carries the session token in the URL (browser path; documented). Follow-up: short-lived download-scoped URLs.
  • Progress-row deletions don't propagate through ?since= deltas (documented; clients treat full refetch as authoritative). Follow-up: tombstones via the hidden-history watermark.
  • Client repos need model/UX work per docs/downloads-api.md §10 (silo-apple) and §11 (silo-android).
  • Known pre-existing flake: playback throttler test under parallel load; passes in isolation.

Testing

go build ./...; downloads/handlers/userstore/userdb/watchstate/playback suites green against a fresh fully-migrated Postgres, including new DB-backed tests (managed-entry auth, quota-before-enqueue, batch registration, LWW conformance on both backends, v11→v12 sqlite trigger upgrade); reshape Down validated against live managed rows; make verify-local-paths, web lint/format pass. Reviewer note: run Go tests in a libvips-capable container for the handlers package per repo checklist.

AI-use disclosure

The adversarial review, the 13 remediation commits, and this PR body were produced with Claude Code (Fable 5) under human direction; the base feature commits predate the review.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added offline sync and managed downloads, including device-scoped download lists, manifests, artwork, subtitles, and subscription-based series downloads.
    • Added download capability checks in the app so clients can see available quality options and limits before starting a download.
    • Added new admin settings for offline sync, prepared downloads, and download quality limits.
  • Bug Fixes

    • Improved progress syncing so updates reconcile more reliably across devices.
    • Strengthened profile deletion cleanup to remove related download data.

Quick104 and others added 18 commits June 19, 2026 08:52
Replace internal/download with a unified internal/downloads package and add
fully-offline download + watch-sync support for mobile clients, across five
independently-shippable phases:

- Phase 0: reshape the downloads table and the /downloads contract to be
  device- and format-aware; add GET /downloads/capability; extend
  DownloadConfig (default-off keys); update the web download hooks/components in
  lockstep. This is the one approved pre-lock exception to the additive-only
  /api/v1 rule (the web app is the only consumer and is updated together).
- Phase 1: managed device-library entries (create/list/PATCH/delete/serve),
  keyed on the X-Silo-Device-Id header.
- Phase 2: offline playback manifest plus artwork/subtitle proxy endpoints that
  strip every presigned URL (inline thumbhashes + authenticated proxies).
- Phase 3: prepare-to-file (remux + transcode-to-single-file) as a durable,
  leased artifact queue with startup recovery, hosted on the task manager;
  playback.PrepareFile emits one +faststart MP4. Adds the admin transcode
  toggle and per-artifact LRU cleanup.
- Phase 4: offline progress reconciliation -- a clamped event_at LWW key plus a
  server-assigned synced_seq cursor on watch_progress; an optional clamped
  updated_at on POST /sync/progress and an opaque ?since= cursor on
  GET /progress (additive; existing callers unaffected).

Security & reliability invariants, each with an acceptance test:
1. Server-owned sync ordering: ?since= delta delivery is driven only by the
   server-assigned synced_seq; the client clock is bounded (event_at, clamped
   to now+skew) and used only for last-write-wins on the caller's own profile.
2. Full profile+device authorization on every managed endpoint, with a
   per-profile content/library access re-check before serving any bytes/assets.
3. Durable artifact recovery: a transactionally-claimed (FOR UPDATE SKIP
   LOCKED), lease-heartbeat, attempt-counted queue with a startup sweep, so no
   crash strands a download in preparing and concurrent workers never
   double-encode.

Migrations are timestamped Goose files: reshape downloads (device/format);
download_artifacts (durable queue); watch_progress event_at/synced_seq.

DB-backed acceptance tests skip without SILO_TEST_DATABASE_URL and run in CI;
the invariant-1 progress test also runs against the real SQLite backend locally.

Client repos (silo-android, silo-apple) consume the reshaped /downloads/*
contract and the updated_at/?since= progress fields and require coordinated
follow-up.

Implements the maintainer-approved v1 capability proposal for offline sync
(downloads v2).

AI-use disclosure: implemented by Claude (Claude Code) from the approved design
doc under docs/superpowers/specs, with human review.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Build season downloads and a "monitor a series" capability on top of the
downloads v2 (offline sync for mobile) work.

Season downloads:
- POST /downloads accepts season_number (with series:true) to download one
  season. CreateSeries/CreateSeason share one body via a listEpisodes closure
  and register managed entries under a shared batch_id (original-only). Episode
  files are resolved in a single batched query.

Series monitoring (auto-download), client-driven:
- New device-scoped download_subscriptions table with a Sonarr-style mode
  (all | future | latest_season | specific_seasons), a client-enforced
  delete_watched flag, and a max_storage_bytes cap. The server never deletes
  on-device files; retention and the hard cap are the client's, the server
  only soft-gates registration.
- The client calls POST /downloads/subscriptions/sync on open / background
  refresh; the server registers the in-scope, not-yet-downloaded episodes
  (idempotent via the managed-entry unique index) and the device pulls them on
  its own schedule. No background worker and no dependency on the notifications
  subsystem. latest_season follows new seasons (>= subscribe-time season);
  future excludes the back catalog via air date.
- Subscription CRUD + sync are profile+device authorized (device id from the
  X-Silo-Device-Id header only) with a per-request content-access re-check. The
  capability endpoint advertises season_download / series_monitoring /
  monitoring_modes.

Also lands the downloads-v2 work already present in the tree: durable artifact
(remux/transcode) preparation and offline watch-progress reconciliation, plus
the design-spec updates.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Artifact IDs are time-sortable, so two artifacts created in the same
moment share their first 8 chars; combined with a captured timestamp the
two preparing-download IDs collided on downloads_pkey. Use the full
artifact ID, which is unique per row.

Co-Authored-By: Claude Fable 5 <[email protected]>
With the sqlite userdb backend, profiles live only in per-user SQLite
stores and public.user_profiles stays empty, so user_devices'
profile FK made every managed create/subscription/offline-sync request
fail with an FK violation. Drop the FK (shared Postgres tables must not
FK profile tables — same rule as notifications) and replace the lost
cascade with an app-level purge on profile deletion, wired through
ProfileHandler for both backends. DB-backed regression tests cover the
no-Postgres-profile-row path and the purge cascade.

Co-Authored-By: Claude Fable 5 <[email protected]>
triggerDrain invoked the kick inline, and the kick (taskmanager RunTask)
executes the encode task on the caller's goroutine — so a POST
/api/v1/downloads with a bitrate quality blocked the HTTP request on the
entire queue drain, ffmpeg encodes included, delaying the 202 by minutes
on an idle queue. Dispatch the kick on a goroutine; the task manager
already serializes concurrent runs.

Co-Authored-By: Claude Fable 5 <[email protected]>
Two gaps let a user bypass MaxConcurrentPerUser entirely for prepared
downloads: artifact-backed rows are created in 'preparing' (never
'queued'/'downloading'), which CountActiveByUser didn't count, and
createArtifactDownload enqueued the encode job before limiter.Check, so
even a 429-rejected request left a job the worker would transcode.
Count 'preparing' as active and check the limiter before Ensure; managed
replacements stay quota-exempt since they don't add a row.

Co-Authored-By: Claude Fable 5 <[email protected]>
HasActiveLink only counted managed (device_id IS NOT NULL) rows, so
under a byte budget Cleanup could delete an artifact still referenced by
a ready-but-unfetched ephemeral web download — permanently 404ing a row
the API kept listing as ready (the artifact row is gone, so recovery
can't re-queue it). Any non-terminal link now protects the artifact;
only artifacts whose links are all cancelled/failed/revoked are
evictable.

Co-Authored-By: Claude Fable 5 <[email protected]>
…hole batch

One deleted or access-filtered episode made GET
/downloads/batches/{id}/manifests 404 for the entire season, so a
client could no longer fetch manifests for the still-valid entries.
Report unbuildable entries in a skipped[] array (revoked | not_found |
error) alongside the delivered manifests, mirroring the create path's
skip idiom. Also cut the batch cost: the shared series detail is
resolved once per batch instead of once per episode, and buildSubtitles
reuses the already-loaded media file instead of re-querying it per
manifest.

Co-Authored-By: Claude Fable 5 <[email protected]>
Under NO TRANSACTION goose splits statements on semicolons, so the
dollar-quoted DO block failed every fresh install with 'unterminated
dollar-quoted string' (SQLSTATE 42601). Already-applied databases are
unaffected. Same fix is being applied to main; identical content merges
cleanly.

Co-Authored-By: Claude Fable 5 <[email protected]>
season_number was a plain int dispatched with '> 0', so requesting the
Specials season was indistinguishable from omitting the field and
silently broadened to a full-series download. Dispatch on pointer
presence, treat 0 as the Specials season, and reject negatives with 400.

Co-Authored-By: Claude Fable 5 <[email protected]>
PresetsFor returned a nil slice when downloads are disabled or the user
lacks the permission, and Capability's []string{} initialization was
immediately overwritten by it — so GET /downloads/capability serialized
"quality_presets": null where the contract documents an array.
Normalize at the source so every caller inherits the guarantee.

Co-Authored-By: Claude Fable 5 <[email protected]>
Three subscription fixes:

- A paused subscription no longer syncs: PATCHing scope (or pausing and
  changing scope in one request) registered episodes for a monitor the
  user had just stopped, inconsistently with SyncSubscriptions' guard.
- SubModeFuture compares calendar days (UTC): air_date is date-only, so
  the strict instant comparison permanently excluded episodes airing the
  same day the user subscribed; episodes with no air date now fall back
  to their ingest time instead of never registering.
- Registration is one batched fetch (GetManagedEntriesByKeys) plus one
  batched INSERT ... ON CONFLICT DO NOTHING RETURNING
  (CreateManagedEntriesBatch) instead of a SELECT+INSERT per episode —
  a 300-episode series cost ~600 sequential round trips per request and
  every no-op sync re-walked the full set. RETURNING yields exactly the
  new rows, so the sync response's 'registered' count now honestly
  reports 0 in the steady state instead of the full in-scope count on
  every app open. The now-unused InsertManagedEntryIfAbsent is removed.

Co-Authored-By: Claude Fable 5 <[email protected]>
MarkProgressBatch (jellycompat series mark-played) advanced updated_at
but never event_at, and both stamp triggers only defaulted event_at when
NULL — so a queued offline event with a client time between the row's
old event_at and the mark could win SetProgressIfNewer and resurrect a
stale resume position that then re-synced to every device.

Make the triggers authoritative instead of adding a tenth hand-written
SET clause: whenever an UPDATE changes updated_at without explicitly
changing event_at, the trigger advances the LWW key; writes that do set
event_at (offline sync's clamped client event time) keep their value.
Postgres gets a CREATE OR REPLACE migration; SQLite gets a v12 userdb
migration that drops and reinstalls the trigger bodies (CREATE TRIGGER
IF NOT EXISTS never replaces). Conformance tests cover both batch paths,
the preserved-client-time invariant, and the v11→v12 upgrade.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tale-row sweeps

Migrations: fold the 20260621 corrective migration back into the base
Downloads V2 migrations (its columns/constraints already exist there)
and fix the reshape Down, which re-added the narrow status CHECK without
collapsing managed-lifecycle rows first — rollback aborted on any DB
with preparing/ready/revoked rows; validated against a live row. Branch
databases that applied the corrective migration need its version row
removed: DELETE FROM goose_db_version WHERE version_id = 20260621020459.

Code: drop the dead 'registered' status (nothing ever wrote it; the
lifecycle is preparing -> ready; 'revoked' stays reserved for the
planned admin revoke flow) along with unused KindDirect and
ErrInvalidFormat.

Sweeps: Cleanup now runs an age-based hygiene pass independent of the
byte budget — cold terminally-failed artifacts (with .part leftovers),
orphaned ready artifacts no download row references, and ephemeral web
rows older than their convenience-record lifetime (also unpinning their
artifacts and bounding GET /downloads growth). The byte budget remains
the disk quota per the limits & restrictions design.

Co-Authored-By: Claude Fable 5 <[email protected]>
…oid handoff

Document the contract changes from the review fixes: batch-manifest
skipped[] shape, honest subscription 'registered' semantics, season 0 =
Specials, always-array quality_presets, bytes_sent actual behavior,
ephemeral 7-day retention, header-pairing requirement, progress-delta
deletion caveat, and the ready/failed push event schema (new §9.4).
Add an Android client handoff section (§11) mirroring the Apple one,
register HEAD on /downloads/{id}/file for download stacks that probe
before ranged GETs, and add season_number to the web create-request
type. Flag the /direct-download session-token-in-URL tradeoff; a
short-lived download-scoped URL is a follow-up.

Co-Authored-By: Claude Fable 5 <[email protected]>
…e sweeps

Behavior-preserving consolidation from the Downloads V2 review:

- appendVideoFilterArgs: one home for the burn-in/hwaccel -vf selection,
  shared by the HLS builder and the single-file prepare builder (the
  drift pattern that already bit tone-mapping once).
- userstore.ResolveProgressState: one home for the min-resume/watched
  threshold rule, replacing five identical copies across both store
  backends and the offline-sync ingest.
- Download file selection ranks resolutions via access.CompareQuality
  (adds 4320p, agrees with playback) instead of a private switch.
- writeSubtitle uses the shared subtitles.SubtitleContentType mapping.
- config.DefaultTranscodeDir replaces three '/tmp/silo-transcode'
  literals.
- Read-side quality/revision defaulting helpers removed: insertArgs plus
  the NOT NULL/CHECK schema already guarantee the invariant.
- Dead code removed: Repository.ListByUser, SubscriptionRepository.
  ListActiveBySeries, and the stale auto-register-worker comments (the
  design is client-pull; no worker exists).
- Redundant left-prefix indexes dropped from the base migrations (their
  unique indexes serve the same prefixes).
- recover()'s disk-presence sweep and the stale-row hygiene sweep run on
  startup then hourly instead of every 30s tick (both are O(cache
  size)).
- gofmt/prettier fixes for pre-existing drift in handlers/playback.go
  and pages/Profiles.tsx.

Deferred (noted for follow-ups): quality-ladder preset table collides
with the drafted download limits & restrictions design, which specifies
its own ladder helper; Download-literal construction consolidation and
the managed-identity value object remain open.

Co-Authored-By: Claude Fable 5 <[email protected]>
Design input for the follow-up v1 capability proposal (quality ceiling,
batch size cap, per-user quantity/bandwidth overrides). Committed with
downloads v2 because the remediation work explicitly defers the quality
ladder refactor and revocation wiring to this spec.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6f6d5962-faca-4b58-93e4-b9c3b6222c0e

📥 Commits

Reviewing files that changed from the base of the PR and between 98b390dbedd770a1804c2ccba37c574598c383d6 and bea99bd.

📒 Files selected for processing (23)
  • .gitignore
  • cmd/silo/main.go
  • docs/downloads-api.md
  • internal/api/handlers/download_subscriptions.go
  • internal/api/handlers/downloads.go
  • internal/api/handlers/progress.go
  • internal/api/router.go
  • internal/downloads/artifact_repo.go
  • internal/downloads/artifacts.go
  • internal/downloads/manifest.go
  • internal/downloads/manifest_test.go
  • internal/downloads/model.go
  • internal/downloads/service.go
  • internal/downloads/subscription_service.go
  • internal/userdb/migrate.go
  • internal/userdb/migrate_v13_test.go
  • internal/userdb/schema.go
  • internal/userdb/sqlitestore.go
  • internal/userstore/pgstore/progress.go
  • internal/userstore/store.go
  • internal/userstore/storetest/suite.go
  • internal/userstore/threshold.go
  • web/src/hooks/queries/keys.ts

📝 Walkthrough

Walkthrough

This PR introduces a "downloads v2" offline sync subsystem, replacing internal/download with internal/downloads. It adds a device-scoped download registry, prepared-file artifact encode pipeline, offline playback manifests, series subscriptions, quality/limits policy, cursor-based progress reconciliation, associated migrations, API handlers/routing, and documentation.

Changes

Downloads v2 offline sync

Layer / File(s) Summary
Core domain model and legacy removal
internal/downloads/model.go, internal/downloads/artifact.go, internal/config/config.go, internal/config/db_loader.go, internal/config/restart_keys_test.go, internal/downloads/bandwidth.go, internal/downloads/limiter.go, internal/download/*.go (removed)
Defines download/artifact status constants, errors, and structs; adds transcode/artifact config fields; renames download package to downloads; removes legacy internal/download.
Migrations
migrations/sql/2026061902..., ...download_artifacts.sql, ...watch_progress_offline_sync.sql, ...download_subscriptions.sql, ...drop_user_devices_profile_fkey.sql, ...advance_event_at_on_write.sql
Reshapes downloads table for device/profile scoping, adds download_artifacts and download_subscriptions tables, and watch-progress cursor/LWW trigger columns.
Repositories
internal/downloads/repo.go, internal/downloads/artifact_repo.go, internal/downloads/repo_managed_test.go, internal/downloads/artifact_repo_test.go
Implements Postgres-backed CRUD, managed-entry authorization, and durable artifact job queue with leasing/retry.
Quality policy and prepare-file encoding
internal/downloads/policy.go, internal/playback/prepare_file.go, internal/playback/transcode.go
Resolves quality/format decisions and builds ffmpeg args for single-file remux/transcode.
Artifact manager and encode task
internal/downloads/artifacts.go, internal/taskmanager/tasks/encode_download_artifacts.go, cmd/silo/main.go
Implements the encode worker pool, lease heartbeats, cleanup/eviction, and wires the recurring task.
Offline manifest and asset serving
internal/downloads/manifest.go, internal/downloads/offline.go, internal/subtitles/manager.go
Builds OfflineManifest DTOs and serves managed artwork/subtitle assets via authorized proxy endpoints.
Series subscriptions
internal/downloads/subscription*.go
Adds subscription model, repository, and sync service for device-scoped series monitoring.
Downloads service orchestration
internal/downloads/service.go
Orchestrates capability, create/list/serve/patch/delete across ephemeral and managed downloads with quota enforcement.
API handlers and router wiring
internal/api/handlers/downloads*.go, internal/api/router.go, internal/api/handlers/profiles.go
Adds/updates HTTP handlers and routes for downloads, subscriptions, and profile device purging.
Progress reconciliation and cursor sync
internal/userdb/*.go, internal/userstore/**, internal/api/handlers/progress.go
Adds event_at/synced_seq LWW semantics and cursor-based delta listing across SQLite/Postgres stores.
Web UI and documentation
web/src/hooks/queries/downloads.ts, web/src/pages/admin-settings/DownloadSettings.tsx, docs/downloads-api.md, docs/superpowers/specs/*
Adds capability hook/settings UI and documents the downloads v2 API/design.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant DownloadHandler
    participant Service as downloads.Service
    participant ArtifactManager
    participant Repo as Repository/ArtifactRepository
    participant Preparer as EncodePreparer

    Client->>DownloadHandler: POST /downloads (quality=transcode)
    DownloadHandler->>Service: Create(userID, req)
    Service->>Service: DownloadQualityResolver.Resolve
    Service->>ArtifactManager: Ensure(file, format, target)
    ArtifactManager->>Repo: EnsureQueued / GetByKey
    Repo-->>ArtifactManager: Artifact (queued)
    ArtifactManager-->>Service: Artifact
    Service->>Repo: CreateManagedEntry (status=preparing)
    Service-->>DownloadHandler: Download (preparing)
    DownloadHandler-->>Client: 202 Accepted

    ArtifactManager->>Repo: ClaimNext (lease)
    ArtifactManager->>Preparer: PrepareFile(opts, outputPath)
    Preparer-->>ArtifactManager: success
    ArtifactManager->>Repo: MarkReady
    ArtifactManager->>Repo: MarkLinkedDownloadsReady
    ArtifactManager-->>Client: EventsHub notification (ready)
Loading
sequenceDiagram
    participant MobileClient
    participant ProgressHandler
    participant UserStore

    MobileClient->>ProgressHandler: POST /sync/progress (updated_at)
    ProgressHandler->>ProgressHandler: clampEventAt(updated_at)
    ProgressHandler->>UserStore: SetProgressIfNewer(clamped event_at)
    UserStore-->>ProgressHandler: applied/skipped (LWW)

    MobileClient->>ProgressHandler: GET /progress?since=cursor
    ProgressHandler->>UserStore: ListProgressSince(cursor)
    UserStore-->>ProgressHandler: rows + next_cursor
    ProgressHandler-->>MobileClient: delta + next_cursor
Loading

Possibly related PRs

  • Silo-Server/silo-server#10: Extends internal/subtitles/manager.go subtitle content/download operations that downloads v2's offline subtitle serving depends on.
  • Silo-Server/silo-server#117: Modifies watch/progress write and completion-threshold logic in the same subsystem now reworked for cursor-based reconciliation.

Suggested labels: v1

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: downloads v2 offline sync for mobile.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/downloads-v2-offline-sync

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

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 2, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 67582a8901

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

if profileID == "" || deviceID == "" {
return nil, ErrProfileRequired
}
sub, err := s.subRepo.GetByID(ctx, id, userID, profileID, deviceID)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Gate subscription updates on download permission

When an existing monitor is patched, this path skips the enabledConfig and user.DownloadAllowed checks that CreateSubscription and SyncSubscriptions perform, but it can still call syncSubscription after mode/season/active/storage changes. If an admin disables downloads or revokes a user's download permission after a subscription exists, that user can PATCH it and register new managed download rows anyway; apply the same feature/user permission gate before mutating or backfilling.

Useful? React with 👍 / 👎.

if file == nil || file.MissingSince != nil {
return catalog.ErrItemNotFound
}
return s.serveLocalFile(ctx, w, r, file.FilePath, userID)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Recheck file-level access before serving managed bytes

For managed downloads, the caller rechecks only dl.ContentID, then this helper streams the stored MediaFileID without applying catalog.FileAllowedByAccess to the current AccessFilter. If a profile's max playback quality or library restrictions change after a row was registered, the device can still download the old 4K or now-disallowed file; mirror the playback/media-file authorizer check before serveLocalFile.

Useful? React with 👍 / 👎.

Comment on lines +237 to +241
if v := pickVersion(detail, dl.MediaFileID); v != nil {
m.Container = v.Container
m.CodecVideo = v.CodecVideo
m.CodecAudio = v.CodecAudio
m.Resolution = v.Resolution

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Describe prepared artifacts instead of source files

For remux/transcode downloads the file endpoint serves the prepared artifact, but the manifest still copies container/codecs/resolution/audio tracks from the original catalog file version. When a HEVC/MKV source is transcoded to MP4/H.264/AAC, mobile clients will store metadata for the wrong local file and may choose the wrong decoder/tracks; artifact-backed manifests should use the linked artifact's prepared parameters.

Useful? React with 👍 / 👎.

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

Actionable comments posted: 7

🧹 Nitpick comments (3)
internal/userstore/storetest/suite.go (1)

947-950: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover UpdateProgress in this event_at invariant too.

This test proves SetProgress advances the LWW key, but UpdateProgress has the same changed online-write contract. Table-driving this block over both methods would prevent one path from regressing unnoticed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/userstore/storetest/suite.go` around lines 947 - 950, The event_at
invariant test only exercises SetProgress, but UpdateProgress follows the same
online-write contract and should be covered too. Update the table-driven block
in the suite around the progress write checks so it runs the same assertion path
for both Store.SetProgress and Store.UpdateProgress, reusing the same scenario
and verifying each method advances the LWW key against the seeded event_at.
internal/api/handlers/downloads.go (1)

346-395: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consolidate HandlePatchDownload's managed-identity checks with requireManaged.

HandlePatchDownload (Lines 349-372) hand-rolls the same auth/service-nil/device_id_required/profile_required sequence that requireManaged (Lines 471-491) already encapsulates for the manifest/artwork/subtitle/batch endpoints. Keeping two copies risks drift if the managed-identity rule changes.

♻️ Suggested consolidation
 func (h *DownloadHandler) HandlePatchDownload(w http.ResponseWriter, r *http.Request) {
-	userID := apimw.GetUserID(r.Context())
-	if userID == 0 {
-		writeError(w, http.StatusUnauthorized, "unauthorized", "Authentication required")
-		return
-	}
+	userID, profileID, deviceID, _, _, ok := h.requireManaged(w, r)
+	if !ok {
+		return
+	}
 	id := chi.URLParam(r, "id")
 	if id == "" {
 		writeError(w, http.StatusBadRequest, "bad_request", "Download ID is required")
 		return
 	}
-	if h.svc == nil {
-		writeError(w, http.StatusServiceUnavailable, "unavailable", "Downloads not configured")
-		return
-	}
-
-	profileID, deviceID, _, _ := managedIdentity(r)
-	if deviceID == "" {
-		writeError(w, http.StatusBadRequest, "device_id_required", "X-Silo-Device-Id header is required")
-		return
-	}
-	if profileID == "" {
-		writeError(w, http.StatusBadRequest, "profile_required", "A profile is required for managed downloads")
-		return
-	}

Also applies to: 471-491

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/downloads.go` around lines 346 - 395,
HandlePatchDownload duplicates the same auth, service availability,
device_id_required, and profile_required checks already centralized in
requireManaged, so the managed-download flow can drift from the other managed
endpoints. Refactor HandlePatchDownload to call requireManaged (or the shared
managed-identity helper path it uses) before decoding the request, and keep the
rest of the status update logic in PatchStatus unchanged. Use the existing
requireManaged helper and HandlePatchDownload as the key symbols when
consolidating the shared validation path.
internal/api/handlers/download_subscriptions.go (1)

99-120: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Consider rejecting negative MaxStorageBytes at the handler boundary.

req.MaxStorageBytes is passed straight through to CreateSubscription with no lower-bound check. A negative value could produce nonsensical storage-quota/eviction behavior downstream. Since subscription_service.go/policy.go aren't in this review batch, it's unclear whether validation happens there; adding a cheap guard here is a safe belt-and-suspenders check regardless.

🛡️ Proposed guard
 	if req.SeriesID == "" {
 		writeError(w, http.StatusBadRequest, "bad_request", "series_id is required")
 		return
 	}
+	if req.MaxStorageBytes < 0 {
+		writeError(w, http.StatusBadRequest, "bad_request", "max_storage_bytes must be non-negative")
+		return
+	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/download_subscriptions.go` around lines 99 - 120,
Reject negative MaxStorageBytes at the handler boundary in downloadSubscriptions
by adding a lower-bound validation before calling h.svc.CreateSubscription; if
req.MaxStorageBytes is below zero, return a bad_request via writeError similar
to the existing series_id check. Use the DownloadSubscriptions handler and the
CreateSubscription call site as the locating symbols, and keep the guard cheap
and explicit so invalid quota values never reach the service layer.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/api/handlers/progress.go`:
- Around line 21-27: The `parseClientEventTime`/`clampEventAt` flow is treating
malformed `updated_at` as a current-time event, which can let bad offline data
win in `SetProgressIfNewer`. Change the sync path in the progress handler so
parse failures for `updated_at` are rejected or skipped instead of returning
zero and clamping to now. Update the event handling around
`parseClientEventTime` and the `updated_at` processing in the sync path to only
accept valid RFC3339 timestamps.

In `@internal/downloads/artifact_repo.go`:
- Around line 234-245: Requeue currently returns nil even when the UPDATE
matches no rows, so callers can treat a deleted artifact as successfully
requeued. Update ArtifactRepository.Requeue to check the Exec result’s affected
row count and return ErrNotFound when zero rows were updated, keeping the
existing error wrapping for real Exec failures. Use the Requeue method in
ArtifactRepository and the ErrNotFound sentinel to locate the fix.

In `@internal/downloads/service.go`:
- Around line 80-108: The Service policy dependency is never initialized before
Capability and Create use it, which can panic at runtime. Update NewService to
accept and assign a DownloadQualityResolver for the policy field, or add a
dedicated wiring method that is called before exposing Capability/Create; make
sure the Service struct’s policy is always populated alongside the other
resolvers used there.
- Around line 501-503: The no-items branch in service.go should return a named
sentinel error instead of a fresh fmt.Errorf so callers can use errors.Is for
HTTP mapping. Update the error path in the function that processes downloadable
episodes to return the existing sentinel pattern used elsewhere in the service,
and ensure the no downloadable episodes case is wrapped or returned consistently
so handlers can match it reliably.

In `@internal/downloads/subscription_service.go`:
- Around line 43-48: The season validation in CreateSubscription and
UpdateSubscription only checks that SeasonNumbers is non-empty, so out-of-range
values can still slip through and later be narrowed by intsToInt32s in
subscription_repo.go. Add a validSeasonNumbers check alongside the existing
specific_seasons length checks in both CreateSubscription and
UpdateSubscription, and return ErrSeasonsRequired or a dedicated sentinel when
validation fails. Use the existing SeasonNumbers handling in these methods to
locate the change.

In `@internal/userstore/pgstore/progress.go`:
- Line 56: Restore the negative-progress guard in the shared resolver used by
both Postgres and SQLite callers. Update userstore.ResolveProgressState so it
clamps or rejects negative position and duration before computing
completed/skip, matching the existing protections in SetProgressAt and
SetProgressIfNewer. Keep the fix centralized in ResolveProgressState so all call
sites, including the one in progress.go, stay consistent.

In `@internal/userstore/threshold.go`:
- Around line 34-43: ResolveProgressState currently classifies negative position
values without normalizing them, which can let invalid progress be persisted.
Update the shared resolver to clamp or normalize negative position input before
applying the MinResumeFraction and WatchedFraction checks, so UpdateProgress and
SetProgress always receive a non-negative resolved position. Keep the change
contained in ResolveProgressState and preserve its existing completed/skip
behavior for valid inputs.

---

Nitpick comments:
In `@internal/api/handlers/download_subscriptions.go`:
- Around line 99-120: Reject negative MaxStorageBytes at the handler boundary in
downloadSubscriptions by adding a lower-bound validation before calling
h.svc.CreateSubscription; if req.MaxStorageBytes is below zero, return a
bad_request via writeError similar to the existing series_id check. Use the
DownloadSubscriptions handler and the CreateSubscription call site as the
locating symbols, and keep the guard cheap and explicit so invalid quota values
never reach the service layer.

In `@internal/api/handlers/downloads.go`:
- Around line 346-395: HandlePatchDownload duplicates the same auth, service
availability, device_id_required, and profile_required checks already
centralized in requireManaged, so the managed-download flow can drift from the
other managed endpoints. Refactor HandlePatchDownload to call requireManaged (or
the shared managed-identity helper path it uses) before decoding the request,
and keep the rest of the status update logic in PatchStatus unchanged. Use the
existing requireManaged helper and HandlePatchDownload as the key symbols when
consolidating the shared validation path.

In `@internal/userstore/storetest/suite.go`:
- Around line 947-950: The event_at invariant test only exercises SetProgress,
but UpdateProgress follows the same online-write contract and should be covered
too. Update the table-driven block in the suite around the progress write checks
so it runs the same assertion path for both Store.SetProgress and
Store.UpdateProgress, reusing the same scenario and verifying each method
advances the LWW key against the seeded event_at.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ffce8e80-774b-4d82-95ac-3041383b677d

📥 Commits

Reviewing files that changed from the base of the PR and between 86adb6a and 67582a8.

📒 Files selected for processing (69)
  • .gitignore
  • cmd/silo/main.go
  • docs/downloads-api.md
  • docs/superpowers/specs/2026-06-18-offline-sync-mobile-design.md
  • docs/superpowers/specs/2026-07-01-download-limits-restrictions-design.md
  • internal/api/handlers/download_subscriptions.go
  • internal/api/handlers/downloads.go
  • internal/api/handlers/downloads_test.go
  • internal/api/handlers/playback.go
  • internal/api/handlers/profiles.go
  • internal/api/handlers/progress.go
  • internal/api/handlers/progress_offline_test.go
  • internal/api/router.go
  • internal/config/config.go
  • internal/config/db_loader.go
  • internal/config/restart_keys_test.go
  • internal/download/model.go
  • internal/download/repo.go
  • internal/download/service.go
  • internal/downloads/artifact.go
  • internal/downloads/artifact_repo.go
  • internal/downloads/artifact_repo_test.go
  • internal/downloads/artifact_test.go
  • internal/downloads/artifacts.go
  • internal/downloads/bandwidth.go
  • internal/downloads/limiter.go
  • internal/downloads/manifest.go
  • internal/downloads/manifest_test.go
  • internal/downloads/model.go
  • internal/downloads/offline.go
  • internal/downloads/offline_batch_test.go
  • internal/downloads/policy.go
  • internal/downloads/policy_test.go
  • internal/downloads/repo.go
  • internal/downloads/repo_managed_test.go
  • internal/downloads/service.go
  • internal/downloads/service_quota_test.go
  • internal/downloads/service_reuse_test.go
  • internal/downloads/subscription.go
  • internal/downloads/subscription_repo.go
  • internal/downloads/subscription_service.go
  • internal/downloads/subscription_test.go
  • internal/playback/prepare_file.go
  • internal/playback/prepare_file_test.go
  • internal/playback/transcode.go
  • internal/subtitles/manager.go
  • internal/taskmanager/tasks/encode_download_artifacts.go
  • internal/userdb/conformance_test.go
  • internal/userdb/migrate.go
  • internal/userdb/migrate_v12_test.go
  • internal/userdb/progress.go
  • internal/userdb/schema.go
  • internal/userdb/sqlitestore.go
  • internal/userstore/pgstore/conformance_test.go
  • internal/userstore/pgstore/progress.go
  • internal/userstore/store.go
  • internal/userstore/storetest/suite.go
  • internal/userstore/threshold.go
  • migrations/sql/20260618164519_add_episodes_season_id_index.sql
  • migrations/sql/20260619020213_reshape_downloads_device_format.sql
  • migrations/sql/20260619030113_download_artifacts.sql
  • migrations/sql/20260619034952_watch_progress_offline_sync.sql
  • migrations/sql/20260619145248_download_subscriptions.sql
  • migrations/sql/20260701225607_drop_user_devices_profile_fkey.sql
  • migrations/sql/20260701232628_advance_event_at_on_write.sql
  • web/src/hooks/queries/downloads.ts
  • web/src/hooks/queries/keys.ts
  • web/src/pages/Profiles.tsx
  • web/src/pages/admin-settings/DownloadSettings.tsx
💤 Files with no reviewable changes (3)
  • internal/download/model.go
  • internal/download/service.go
  • internal/download/repo.go

Comment thread internal/api/handlers/progress.go Resolved
Comment thread internal/downloads/artifact_repo.go Resolved
Comment on lines +80 to +108
type Service struct {
repo *Repository
policy DownloadQualityResolver
bandwidth *BandwidthManager
limiter *QuantityLimiter
fileRepo FileResolver
itemRepo ItemResolver
episodeRepo EpisodeResolver
userRepo UserResolver
itemAccess ItemAccessChecker
settings SettingsReader

// Offline-manifest dependencies (Phase 2); nil until SetOfflineDeps wires them.
manifest *ManifestBuilder
subtitleSource SubtitleSource
artworkSource ManifestSource
httpClient *http.Client

// Prepare-to-file pipeline (Phase 3); nil until SetArtifactManager wires it.
artifacts *ArtifactManager

// Series-monitoring subscriptions (auto-download); nil until SetSubscriptions
// wires the repo, in which case the subscription endpoints report unavailable.
subRepo *SubscriptionRepository

cfgMu sync.RWMutex
cfg config.DownloadConfig
cfgLoadedAt time.Time
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Confirm where (if anywhere) Service.policy gets assigned.
rg -n "policy\s+DownloadQualityResolver" internal/downloads
rg -n "func \(s \*Service\) SetPolicy" internal/downloads
rg -n "\.policy\s*=" internal/downloads
rg -n "NewService\(" -A 15 cmd/silo/main.go

Repository: Silo-Server/silo-server

Length of output: 8597


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== internal/downloads file map =="
fd -a . internal/downloads

echo
echo "== service.go outline =="
ast-grep outline internal/downloads/service.go --view expanded

echo
echo "== search for policy wiring across repo =="
rg -n "(\.policy\s*=|SetPolicy\(|DownloadQualityResolver|PresetsFor\(|Resolve\()"

Repository: Silo-Server/silo-server

Length of output: 8466


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== constructor and policy call sites =="
sed -n '138,330p' internal/downloads/service.go

echo
echo "== policy interface and implementation =="
sed -n '1,220p' internal/downloads/policy.go

echo
echo "== all downloads service constructors =="
rg -n "downloads\.NewService|NewService\(" internal cmd -g '!**/*_test.go'

echo
echo "== any policy assignment or setter outside internal/downloads =="
rg -n "\.policy\s*=|SetPolicy\(" .

Repository: Silo-Server/silo-server

Length of output: 16340


Wire policy into Service before Capability/Create run
policy is never set in NewService, there’s no setter, and nothing else in the repo assigns it. Both Capability and Create call it unconditionally, so any request reaching either path will panic. Pass the resolver into NewService or wire it before those methods are exposed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/downloads/service.go` around lines 80 - 108, The Service policy
dependency is never initialized before Capability and Create use it, which can
panic at runtime. Update NewService to accept and assign a
DownloadQualityResolver for the policy field, or add a dedicated wiring method
that is called before exposing Capability/Create; make sure the Service struct’s
policy is always populated alongside the other resolvers used there.

Comment thread internal/downloads/service.go Resolved
Comment thread internal/userstore/pgstore/progress.go Resolved
Comment thread internal/userstore/threshold.go Resolved
Quick104 added 2 commits July 1, 2026 21:16
…nputs

Review findings on #258:

- A malformed (non-RFC3339) updated_at in POST /sync/progress previously
  parsed to the zero time, which clampEventAt treated as "now" — letting a
  stale offline event win LWW as a fresh server-time write. The item is now
  rejected with a per-item error instead.
- ResolveProgressState now clamps negative position/duration before
  classification so no backend can persist negative progress through
  UpdateProgress/SetProgress.
- The online-write event_at invariant test is table-driven over both
  SetProgress and UpdateProgress, which share the same contract.

Co-Authored-By: Claude Fable 5 <[email protected]>
…heck, artifact-true manifests

Review findings on #258:

- UpdateSubscription now applies the same feature/DownloadAllowed gate as
  CreateSubscription and SyncSubscriptions; a PATCH could previously
  re-activate or widen a monitor and register managed rows after an admin
  disabled downloads or revoked the user.
- Serving download bytes (managed and ephemeral) and /direct-download now
  mirror playback's per-file authorization via catalog.FileAllowedByAccess:
  library scope and the profile's max playback quality are re-checked at
  serve time, with artifact-backed rows checked against the artifact's
  resolution (a 720p transcode of a 4K source stays servable under a 1080p
  ceiling).
- Offline manifests for remux/transcode entries now describe the prepared
  artifact (container, codecs, resolution, single selected audio track)
  instead of the catalog source file the client never receives.
- ArtifactRepository.Requeue reports ErrNotFound when the row was
  concurrently swept; ArtifactManager.Ensure recreates the job in that case
  instead of linking downloads to a dead artifact id.
- "No downloadable episodes" is a sentinel (mapped to 404
  no_downloadable_episodes) rather than a bare error that surfaced as 500.
- Subscription season_numbers are bounds-checked (0–9999) before the int32
  narrowing in the repo could silently wrap them.
- HandlePatchDownload reuses requireManaged instead of hand-rolling the
  same managed-identity checks.

Co-Authored-By: Claude Fable 5 <[email protected]>

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/api/handlers/progress.go (1)

350-363: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Only mark actual LWW writes as successful updates.

Line 350 discards the SetProgressIfNewer boolean, so stale offline events that were ignored still set hadSuccessfulUpdate on Line 363. Track the applied flag and only trigger refresh/events for items that actually changed state.

Proposed fix
-			if !skip {
-				_, updateErr = store.SetProgressIfNewer(r.Context(), profileID, item.MediaItemID, pos, item.Duration, completed, eventAt)
+			didUpdate := false
+			if !skip {
+				didUpdate, updateErr = store.SetProgressIfNewer(r.Context(), profileID, item.MediaItemID, pos, item.Duration, completed, eventAt)
 			}

Then only set hadSuccessfulUpdate when didUpdate is true for this branch.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/progress.go` around lines 350 - 363, The progress
update flow in the handler around SetProgressIfNewer is treating ignored stale
LWW writes as successful updates because the returned applied flag is discarded.
Update the progress switch in progress.go so the SetProgressIfNewer branch
captures the boolean result from store.SetProgressIfNewer, and only set
hadSuccessfulUpdate (and any downstream refresh/event behavior) when that flag
indicates the item actually changed state; keep the ForceOverwrite and
UpdateProgress branches unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/downloads/manifest.go`:
- Around line 255-258: The artifact-backed manifest path in prepareManifest
should fail closed instead of silently falling back when b.artifact(ctx,
dl.ArtifactID) errors or returns nil. Update the non-original dl.Format branch
in prepareManifest to treat any unresolved artifact as an error for
remux/transcode downloads, and only call applyArtifactParams when a valid
artifact is returned; otherwise return a descriptive error so the manifest
cannot describe the wrong delivered file.

---

Outside diff comments:
In `@internal/api/handlers/progress.go`:
- Around line 350-363: The progress update flow in the handler around
SetProgressIfNewer is treating ignored stale LWW writes as successful updates
because the returned applied flag is discarded. Update the progress switch in
progress.go so the SetProgressIfNewer branch captures the boolean result from
store.SetProgressIfNewer, and only set hadSuccessfulUpdate (and any downstream
refresh/event behavior) when that flag indicates the item actually changed
state; keep the ForceOverwrite and UpdateProgress branches unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8d5eb5e4-55cb-4820-818b-44634ff18f97

📥 Commits

Reviewing files that changed from the base of the PR and between 67582a8 and 98b390dbedd770a1804c2ccba37c574598c383d6.

📒 Files selected for processing (13)
  • docs/downloads-api.md
  • internal/api/handlers/download_subscriptions.go
  • internal/api/handlers/downloads.go
  • internal/api/handlers/progress.go
  • internal/downloads/artifact_repo.go
  • internal/downloads/artifacts.go
  • internal/downloads/manifest.go
  • internal/downloads/manifest_test.go
  • internal/downloads/model.go
  • internal/downloads/service.go
  • internal/downloads/subscription_service.go
  • internal/userstore/storetest/suite.go
  • internal/userstore/threshold.go
🚧 Files skipped from review as they are similar to previous changes (11)
  • internal/userstore/threshold.go
  • internal/downloads/manifest_test.go
  • internal/api/handlers/download_subscriptions.go
  • internal/userstore/storetest/suite.go
  • internal/downloads/model.go
  • docs/downloads-api.md
  • internal/downloads/subscription_service.go
  • internal/downloads/artifact_repo.go
  • internal/downloads/artifacts.go
  • internal/downloads/service.go
  • internal/api/handlers/downloads.go

Comment on lines +255 to +258
if dl.Format != FormatOriginal && dl.ArtifactID != "" && b.artifact != nil {
if a, err := b.artifact(ctx, dl.ArtifactID); err == nil && a != nil {
applyArtifactParams(m, a)
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Fail closed when a prepared artifact cannot be resolved.

Line 256 silently falls back to source-file metadata if the artifact lookup errors or returns nil, so a remux/transcode manifest can describe the wrong delivered file. Return an error instead for artifact-backed non-original downloads.

Proposed fix
-	if dl.Format != FormatOriginal && dl.ArtifactID != "" && b.artifact != nil {
-		if a, err := b.artifact(ctx, dl.ArtifactID); err == nil && a != nil {
-			applyArtifactParams(m, a)
-		}
+	if dl.Format != FormatOriginal && dl.ArtifactID != "" {
+		if b.artifact == nil {
+			return nil, fmt.Errorf("artifact resolver unavailable for download %s", dl.ID)
+		}
+		a, err := b.artifact(ctx, dl.ArtifactID)
+		if err != nil {
+			return nil, err
+		}
+		if a == nil {
+			return nil, fmt.Errorf("artifact %s not found", dl.ArtifactID)
+		}
+		applyArtifactParams(m, a)
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if dl.Format != FormatOriginal && dl.ArtifactID != "" && b.artifact != nil {
if a, err := b.artifact(ctx, dl.ArtifactID); err == nil && a != nil {
applyArtifactParams(m, a)
}
if dl.Format != FormatOriginal && dl.ArtifactID != "" {
if b.artifact == nil {
return nil, fmt.Errorf("artifact resolver unavailable for download %s", dl.ID)
}
a, err := b.artifact(ctx, dl.ArtifactID)
if err != nil {
return nil, err
}
if a == nil {
return nil, fmt.Errorf("artifact %s not found", dl.ArtifactID)
}
applyArtifactParams(m, a)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/downloads/manifest.go` around lines 255 - 258, The artifact-backed
manifest path in prepareManifest should fail closed instead of silently falling
back when b.artifact(ctx, dl.ArtifactID) errors or returns nil. Update the
non-original dl.Format branch in prepareManifest to treat any unresolved
artifact as an error for remux/transcode downloads, and only call
applyArtifactParams when a valid artifact is returned; otherwise return a
descriptive error so the manifest cannot describe the wrong delivered file.

Both branches added a userdb migrateToV12 (main: watchlist.sort_index;
this branch: watch_progress stamp-trigger replacement). Kept main's v12
and renumbered the trigger migration to v13, bumping schemaVersion to 13.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104
Quick104 force-pushed the feat/downloads-v2-offline-sync branch from e410004 to bea99bd Compare July 2, 2026 02:01
@Quick104
Quick104 merged commit b1b3a9b into main Jul 2, 2026
1 check was pending
@Quick104
Quick104 deleted the feat/downloads-v2-offline-sync branch July 2, 2026 02:05
Quick104 added a commit that referenced this pull request Jul 2, 2026
…vity view (#262)

* test(jellycompat): implement ListProgressSince on userstore test fake

PR #258 added ListProgressSince to the userstore.UserStore interface but
missed the progressCountingStore stub, leaving the jellycompat test build
broken on main. Stub it with the same panic("unused") the sibling methods
use.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(jellycompat): keep still-playing direct-play sessions in the activity view

An Infuse Static=true direct play skips PlaybackInfo, so its playback
reports carry a client-generated PlaySessionId. handlePlaybackReport only
resolved reports by exact PlaySessionId, so every report silently no-op'd:
the admin Activity View position froze, nothing refreshed the upstream
session's activity, and stale cleanup reaped the session ~45s in while the
client kept playing. Once reaped, ensureUpstreamPlayback early-returned the
dangling session id forever, so the stream card never came back.

Fix all three legs:
- handlePlaybackReport falls back to the same token-scoped route lookup the
  stream path uses (ItemId, then MediaSourceId) when the PlaySessionId is
  unknown, and revives a reaped upstream session when a progress report
  proves the client is still playing.
- HandleVideoStream marks an in-flight media transport around direct-play
  and remux serving, mirroring the native stream handler, so long-lived
  range transfers keep the session alive without progress reports.
- ensureUpstreamPlayback verifies the upstream session still exists before
  reusing it, recreating it under the same play session when it was reaped.

FindByRoute now compares RouteItemID with UUID normalization so report ids
match regardless of client dash/case formatting.

Closes #244

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(jellycompat): harden report fallback and upstream revive per adversarial review

Address three review findings on the issue #244 fix:

- Deterministic report binding: the stream path now records the client's
  own PlaySessionId (Static=true direct play never learns the server id)
  as an alias on the play session it binds, and playback reports resolve
  by that alias before falling back to the ambiguous item/source route
  scan. A Stopped report that only matched by bare route no longer tears
  the session down (it may not own it when the same item plays twice
  under one token); stale cleanup owns that path.
- Same-method revive closes any transcode still keyed to the reaped
  upstream id before recreating the session, so a second ffmpeg cannot
  start alongside an orphaned one.
- Attaching a new upstream session is now a compare-and-swap on the
  observed upstream id: the loser of a concurrent revive/range-request
  race stops its session and adopts the winner instead of leaving an
  orphan counted against the user's stream limits.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(jellycompat): guard alias ambiguity and method switches in upstream attach

Second-round adversarial findings on the issue #244 fix:

- A client PlaySessionId alias now only resolves when it identifies
  exactly one live session for the token, and the candidate must agree
  with the report's ItemId/MediaSourceId. A reused or stale client id
  degrades to the route scan (progress still lands on the right item)
  instead of binding an arbitrary session, and an ambiguous Stopped
  report tears nothing down.
- A CAS loser only adopts the concurrent winner when it serves the same
  play method; a concurrent method switch surfaces 409 Conflict instead
  of continuing with mismatched transcode bookkeeping.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(jellycompat): key audio-selection updates by the resolved play session id

Review follow-up (PR #262): after an alias or route fallback,
req.PlaySessionID is the client's own generated id and not a playback
store key, so the audio-track-change branch in handlePlaybackReport
silently dropped selection updates for Static direct-play sessions.
Use the resolved playSession.ID for the store mutation and logging.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Quick104 pushed a commit that referenced this pull request Jul 2, 2026
PR #258 added ListProgressSince to the userstore.UserStore interface but
did not update the access resolver test stub, breaking test compilation
for internal/access on main.

Co-authored-by: Claude Fable 5 <[email protected]>
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
)

* feat(downloads): offline sync for mobile (downloads v2)

Replace internal/download with a unified internal/downloads package and add
fully-offline download + watch-sync support for mobile clients, across five
independently-shippable phases:

- Phase 0: reshape the downloads table and the /downloads contract to be
  device- and format-aware; add GET /downloads/capability; extend
  DownloadConfig (default-off keys); update the web download hooks/components in
  lockstep. This is the one approved pre-lock exception to the additive-only
  /api/v1 rule (the web app is the only consumer and is updated together).
- Phase 1: managed device-library entries (create/list/PATCH/delete/serve),
  keyed on the X-Silo-Device-Id header.
- Phase 2: offline playback manifest plus artwork/subtitle proxy endpoints that
  strip every presigned URL (inline thumbhashes + authenticated proxies).
- Phase 3: prepare-to-file (remux + transcode-to-single-file) as a durable,
  leased artifact queue with startup recovery, hosted on the task manager;
  playback.PrepareFile emits one +faststart MP4. Adds the admin transcode
  toggle and per-artifact LRU cleanup.
- Phase 4: offline progress reconciliation -- a clamped event_at LWW key plus a
  server-assigned synced_seq cursor on watch_progress; an optional clamped
  updated_at on POST /sync/progress and an opaque ?since= cursor on
  GET /progress (additive; existing callers unaffected).

Security & reliability invariants, each with an acceptance test:
1. Server-owned sync ordering: ?since= delta delivery is driven only by the
   server-assigned synced_seq; the client clock is bounded (event_at, clamped
   to now+skew) and used only for last-write-wins on the caller's own profile.
2. Full profile+device authorization on every managed endpoint, with a
   per-profile content/library access re-check before serving any bytes/assets.
3. Durable artifact recovery: a transactionally-claimed (FOR UPDATE SKIP
   LOCKED), lease-heartbeat, attempt-counted queue with a startup sweep, so no
   crash strands a download in preparing and concurrent workers never
   double-encode.

Migrations are timestamped Goose files: reshape downloads (device/format);
download_artifacts (durable queue); watch_progress event_at/synced_seq.

DB-backed acceptance tests skip without SILO_TEST_DATABASE_URL and run in CI;
the invariant-1 progress test also runs against the real SQLite backend locally.

Client repos (silo-android, silo-apple) consume the reshaped /downloads/*
contract and the updated_at/?since= progress fields and require coordinated
follow-up.

Implements the maintainer-approved v1 capability proposal for offline sync
(downloads v2).

AI-use disclosure: implemented by Claude (Claude Code) from the approved design
doc under docs/superpowers/specs, with human review.

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

* feat(downloads): series & season downloads + client-pull monitoring

Build season downloads and a "monitor a series" capability on top of the
downloads v2 (offline sync for mobile) work.

Season downloads:
- POST /downloads accepts season_number (with series:true) to download one
  season. CreateSeries/CreateSeason share one body via a listEpisodes closure
  and register managed entries under a shared batch_id (original-only). Episode
  files are resolved in a single batched query.

Series monitoring (auto-download), client-driven:
- New device-scoped download_subscriptions table with a Sonarr-style mode
  (all | future | latest_season | specific_seasons), a client-enforced
  delete_watched flag, and a max_storage_bytes cap. The server never deletes
  on-device files; retention and the hard cap are the client's, the server
  only soft-gates registration.
- The client calls POST /downloads/subscriptions/sync on open / background
  refresh; the server registers the in-scope, not-yet-downloaded episodes
  (idempotent via the managed-entry unique index) and the device pulls them on
  its own schedule. No background worker and no dependency on the notifications
  subsystem. latest_season follows new seasons (>= subscribe-time season);
  future excludes the back catalog via air date.
- Subscription CRUD + sync are profile+device authorized (device id from the
  X-Silo-Device-Id header only) with a per-request content-access re-check. The
  capability endpoint advertises season_download / series_monitoring /
  monitoring_modes.

Also lands the downloads-v2 work already present in the tree: durable artifact
(remux/transcode) preparation and offline watch-progress reconciliation, plus
the design-spec updates.

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

* WIP: epitaxy pre-switch from feat/downloads-v2-offline-sync

* test(downloads): fix deterministic ID collision in reconcile test

Artifact IDs are time-sortable, so two artifacts created in the same
moment share their first 8 chars; combined with a captured timestamp the
two preparing-download IDs collided on downloads_pkey. Use the full
artifact ID, which is unique per row.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(downloads): support sqlite userdb backend for managed downloads

With the sqlite userdb backend, profiles live only in per-user SQLite
stores and public.user_profiles stays empty, so user_devices'
profile FK made every managed create/subscription/offline-sync request
fail with an FK violation. Drop the FK (shared Postgres tables must not
FK profile tables — same rule as notifications) and replace the lost
cascade with an app-level purge on profile deletion, wired through
ProfileHandler for both backends. DB-backed regression tests cover the
no-Postgres-profile-row path and the purge cascade.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(downloads): dispatch encode kick asynchronously

triggerDrain invoked the kick inline, and the kick (taskmanager RunTask)
executes the encode task on the caller's goroutine — so a POST
/api/v1/downloads with a bitrate quality blocked the HTTP request on the
entire queue drain, ffmpeg encodes included, delaying the 202 by minutes
on an idle queue. Dispatch the kick on a goroutine; the task manager
already serializes concurrent runs.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(downloads): enforce per-user quota on the encode pipeline

Two gaps let a user bypass MaxConcurrentPerUser entirely for prepared
downloads: artifact-backed rows are created in 'preparing' (never
'queued'/'downloading'), which CountActiveByUser didn't count, and
createArtifactDownload enqueued the encode job before limiter.Check, so
even a 429-rejected request left a job the worker would transcode.
Count 'preparing' as active and check the limiter before Ensure; managed
replacements stay quota-exempt since they don't add a row.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(downloads): protect ephemeral artifact links from LRU eviction

HasActiveLink only counted managed (device_id IS NOT NULL) rows, so
under a byte budget Cleanup could delete an artifact still referenced by
a ready-but-unfetched ephemeral web download — permanently 404ing a row
the API kept listing as ready (the artifact row is gone, so recovery
can't re-queue it). Any non-terminal link now protects the artifact;
only artifacts whose links are all cancelled/failed/revoked are
evictable.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(downloads): batch manifests skip bad entries instead of failing whole batch

One deleted or access-filtered episode made GET
/downloads/batches/{id}/manifests 404 for the entire season, so a
client could no longer fetch manifests for the still-valid entries.
Report unbuildable entries in a skipped[] array (revoked | not_found |
error) alongside the delivered manifests, mirroring the create path's
skip idiom. Also cut the batch cost: the shared series detail is
resolved once per batch instead of once per episode, and buildSubtitles
reuses the already-loaded media file instead of re-querying it per
manifest.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(migrations): wrap DO block in StatementBegin/End markers

Under NO TRANSACTION goose splits statements on semicolons, so the
dollar-quoted DO block failed every fresh install with 'unterminated
dollar-quoted string' (SQLSTATE 42601). Already-applied databases are
unaffected. Same fix is being applied to main; identical content merges
cleanly.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(api): allow season 0 (Specials) in season downloads

season_number was a plain int dispatched with '> 0', so requesting the
Specials season was indistinguishable from omitting the field and
silently broadened to a full-series download. Dispatch on pointer
presence, treat 0 as the Specials season, and reject negatives with 400.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(downloads): capability quality_presets is never JSON null

PresetsFor returned a nil slice when downloads are disabled or the user
lacks the permission, and Capability's []string{} initialization was
immediately overwritten by it — so GET /downloads/capability serialized
"quality_presets": null where the contract documents an array.
Normalize at the source so every caller inherits the guarantee.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(downloads): subscription sync correctness + batched registration

Three subscription fixes:

- A paused subscription no longer syncs: PATCHing scope (or pausing and
  changing scope in one request) registered episodes for a monitor the
  user had just stopped, inconsistently with SyncSubscriptions' guard.
- SubModeFuture compares calendar days (UTC): air_date is date-only, so
  the strict instant comparison permanently excluded episodes airing the
  same day the user subscribed; episodes with no air date now fall back
  to their ingest time instead of never registering.
- Registration is one batched fetch (GetManagedEntriesByKeys) plus one
  batched INSERT ... ON CONFLICT DO NOTHING RETURNING
  (CreateManagedEntriesBatch) instead of a SELECT+INSERT per episode —
  a 300-episode series cost ~600 sequential round trips per request and
  every no-op sync re-walked the full set. RETURNING yields exactly the
  new rows, so the sync response's 'registered' count now honestly
  reports 0 in the steady state instead of the full in-scope count on
  every app open. The now-unused InsertManagedEntryIfAbsent is removed.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(userstore): stamp triggers own the event_at LWW key

MarkProgressBatch (jellycompat series mark-played) advanced updated_at
but never event_at, and both stamp triggers only defaulted event_at when
NULL — so a queued offline event with a client time between the row's
old event_at and the mark could win SetProgressIfNewer and resurrect a
stale resume position that then re-synced to every device.

Make the triggers authoritative instead of adding a tenth hand-written
SET clause: whenever an UPDATE changes updated_at without explicitly
changing event_at, the trigger advances the LWW key; writes that do set
event_at (offline sync's clamped client event time) keep their value.
Postgres gets a CREATE OR REPLACE migration; SQLite gets a v12 userdb
migration that drops and reinstalls the trigger bodies (CREATE TRIGGER
IF NOT EXISTS never replaces). Conformance tests cover both batch paths,
the preserved-client-time invariant, and the v11→v12 upgrade.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(downloads): lifecycle hygiene — squash migrations, dead status, stale-row sweeps

Migrations: fold the 20260621 corrective migration back into the base
Downloads V2 migrations (its columns/constraints already exist there)
and fix the reshape Down, which re-added the narrow status CHECK without
collapsing managed-lifecycle rows first — rollback aborted on any DB
with preparing/ready/revoked rows; validated against a live row. Branch
databases that applied the corrective migration need its version row
removed: DELETE FROM goose_db_version WHERE version_id = 20260621020459.

Code: drop the dead 'registered' status (nothing ever wrote it; the
lifecycle is preparing -> ready; 'revoked' stays reserved for the
planned admin revoke flow) along with unused KindDirect and
ErrInvalidFormat.

Sweeps: Cleanup now runs an age-based hygiene pass independent of the
byte budget — cold terminally-failed artifacts (with .part leftovers),
orphaned ready artifacts no download row references, and ephemeral web
rows older than their convenience-record lifetime (also unpinning their
artifacts and bounding GET /downloads growth). The byte budget remains
the disk quota per the limits & restrictions design.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(downloads): sync API doc with v2 fixes; HEAD on file route; Android handoff

Document the contract changes from the review fixes: batch-manifest
skipped[] shape, honest subscription 'registered' semantics, season 0 =
Specials, always-array quality_presets, bytes_sent actual behavior,
ephemeral 7-day retention, header-pairing requirement, progress-delta
deletion caveat, and the ready/failed push event schema (new §9.4).
Add an Android client handoff section (§11) mirroring the Apple one,
register HEAD on /downloads/{id}/file for download stacks that probe
before ranged GETs, and add season_number to the web create-request
type. Flag the /direct-download session-token-in-URL tradeoff; a
short-lived download-scoped URL is a follow-up.

Co-Authored-By: Claude Fable 5 <[email protected]>

* refactor: consolidate download/progress helpers, prune dead code, gate sweeps

Behavior-preserving consolidation from the Downloads V2 review:

- appendVideoFilterArgs: one home for the burn-in/hwaccel -vf selection,
  shared by the HLS builder and the single-file prepare builder (the
  drift pattern that already bit tone-mapping once).
- userstore.ResolveProgressState: one home for the min-resume/watched
  threshold rule, replacing five identical copies across both store
  backends and the offline-sync ingest.
- Download file selection ranks resolutions via access.CompareQuality
  (adds 4320p, agrees with playback) instead of a private switch.
- writeSubtitle uses the shared subtitles.SubtitleContentType mapping.
- config.DefaultTranscodeDir replaces three '/tmp/silo-transcode'
  literals.
- Read-side quality/revision defaulting helpers removed: insertArgs plus
  the NOT NULL/CHECK schema already guarantee the invariant.
- Dead code removed: Repository.ListByUser, SubscriptionRepository.
  ListActiveBySeries, and the stale auto-register-worker comments (the
  design is client-pull; no worker exists).
- Redundant left-prefix indexes dropped from the base migrations (their
  unique indexes serve the same prefixes).
- recover()'s disk-presence sweep and the stale-row hygiene sweep run on
  startup then hourly instead of every 30s tick (both are O(cache
  size)).
- gofmt/prettier fixes for pre-existing drift in handlers/playback.go
  and pages/Profiles.tsx.

Deferred (noted for follow-ups): quality-ladder preset table collides
with the drafted download limits & restrictions design, which specifies
its own ladder helper; Download-literal construction consolidation and
the managed-identity value object remain open.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(downloads): draft download limits & restrictions design

Design input for the follow-up v1 capability proposal (quality ceiling,
batch size cap, per-user quantity/bandwidth overrides). Committed with
downloads v2 because the remediation work explicitly defers the quality
ladder refactor and revocation wiring to this spec.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(progress): reject malformed updated_at; clamp negative progress inputs

Review findings on Silo-Server#258:

- A malformed (non-RFC3339) updated_at in POST /sync/progress previously
  parsed to the zero time, which clampEventAt treated as "now" — letting a
  stale offline event win LWW as a fresh server-time write. The item is now
  rejected with a per-item error instead.
- ResolveProgressState now clamps negative position/duration before
  classification so no backend can persist negative progress through
  UpdateProgress/SetProgress.
- The online-write event_at invariant test is table-driven over both
  SetProgress and UpdateProgress, which share the same contract.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(downloads): close review gaps — permission gates, file-access recheck, artifact-true manifests

Review findings on Silo-Server#258:

- UpdateSubscription now applies the same feature/DownloadAllowed gate as
  CreateSubscription and SyncSubscriptions; a PATCH could previously
  re-activate or widen a monitor and register managed rows after an admin
  disabled downloads or revoked the user.
- Serving download bytes (managed and ephemeral) and /direct-download now
  mirror playback's per-file authorization via catalog.FileAllowedByAccess:
  library scope and the profile's max playback quality are re-checked at
  serve time, with artifact-backed rows checked against the artifact's
  resolution (a 720p transcode of a 4K source stays servable under a 1080p
  ceiling).
- Offline manifests for remux/transcode entries now describe the prepared
  artifact (container, codecs, resolution, single selected audio track)
  instead of the catalog source file the client never receives.
- ArtifactRepository.Requeue reports ErrNotFound when the row was
  concurrently swept; ArtifactManager.Ensure recreates the job in that case
  instead of linking downloads to a dead artifact id.
- "No downloadable episodes" is a sentinel (mapped to 404
  no_downloadable_episodes) rather than a bare error that surfaced as 500.
- Subscription season_numbers are bounds-checked (0–9999) before the int32
  narrowing in the repo could silently wrap them.
- HandlePatchDownload reuses requireManaged instead of hand-rolling the
  same managed-identity checks.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…vity view (Silo-Server#262)

* test(jellycompat): implement ListProgressSince on userstore test fake

PR Silo-Server#258 added ListProgressSince to the userstore.UserStore interface but
missed the progressCountingStore stub, leaving the jellycompat test build
broken on main. Stub it with the same panic("unused") the sibling methods
use.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(jellycompat): keep still-playing direct-play sessions in the activity view

An Infuse Static=true direct play skips PlaybackInfo, so its playback
reports carry a client-generated PlaySessionId. handlePlaybackReport only
resolved reports by exact PlaySessionId, so every report silently no-op'd:
the admin Activity View position froze, nothing refreshed the upstream
session's activity, and stale cleanup reaped the session ~45s in while the
client kept playing. Once reaped, ensureUpstreamPlayback early-returned the
dangling session id forever, so the stream card never came back.

Fix all three legs:
- handlePlaybackReport falls back to the same token-scoped route lookup the
  stream path uses (ItemId, then MediaSourceId) when the PlaySessionId is
  unknown, and revives a reaped upstream session when a progress report
  proves the client is still playing.
- HandleVideoStream marks an in-flight media transport around direct-play
  and remux serving, mirroring the native stream handler, so long-lived
  range transfers keep the session alive without progress reports.
- ensureUpstreamPlayback verifies the upstream session still exists before
  reusing it, recreating it under the same play session when it was reaped.

FindByRoute now compares RouteItemID with UUID normalization so report ids
match regardless of client dash/case formatting.

Closes Silo-Server#244

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(jellycompat): harden report fallback and upstream revive per adversarial review

Address three review findings on the issue Silo-Server#244 fix:

- Deterministic report binding: the stream path now records the client's
  own PlaySessionId (Static=true direct play never learns the server id)
  as an alias on the play session it binds, and playback reports resolve
  by that alias before falling back to the ambiguous item/source route
  scan. A Stopped report that only matched by bare route no longer tears
  the session down (it may not own it when the same item plays twice
  under one token); stale cleanup owns that path.
- Same-method revive closes any transcode still keyed to the reaped
  upstream id before recreating the session, so a second ffmpeg cannot
  start alongside an orphaned one.
- Attaching a new upstream session is now a compare-and-swap on the
  observed upstream id: the loser of a concurrent revive/range-request
  race stops its session and adopts the winner instead of leaving an
  orphan counted against the user's stream limits.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(jellycompat): guard alias ambiguity and method switches in upstream attach

Second-round adversarial findings on the issue Silo-Server#244 fix:

- A client PlaySessionId alias now only resolves when it identifies
  exactly one live session for the token, and the candidate must agree
  with the report's ItemId/MediaSourceId. A reused or stale client id
  degrades to the route scan (progress still lands on the right item)
  instead of binding an arbitrary session, and an ambiguous Stopped
  report tears nothing down.
- A CAS loser only adopts the concurrent winner when it serves the same
  play method; a concurrent method switch surfaces 409 Conflict instead
  of continuing with mismatched transcode bookkeeping.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(jellycompat): key audio-selection updates by the resolved play session id

Review follow-up (PR Silo-Server#262): after an alias or route fallback,
req.PlaySessionID is the client's own generated id and not a playback
store key, so the audio-track-change branch in handlePlaybackReport
silently dropped selection updates for Static direct-play sessions.
Use the resolved playSession.ID for the store mutation and logging.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Quick104 pushed a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…lo-Server#277)

PR Silo-Server#258 added ListProgressSince to the userstore.UserStore interface but
did not update the access resolver test stub, breaking test compilation
for internal/access on main.

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant