Skip to content

fix(downloads): queue season and series downloads over the concurrent limit - #1713

Merged
Quick104 merged 1 commit into
Silo-Server:mainfrom
Rhainland:fix/season-download-queue-over-limit
Oct 5, 2026
Merged

Quick104 merged 1 commit into
Silo-Server:mainfrom
Rhainland:fix/season-download-queue-over-limit

Conversation

@Rhainland

@Rhainland Rhainland commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #1703
Related issue: #1167
Validation tasks: none (#1217 C1 and #1218 C1 cover the concurrent limit and have not been run)

"Download Season" on iOS and "Download series" on Android fail whenever the season or series has more episodes than the per-user concurrent download limit (download.max_concurrent_per_user, default 3). The server rejects the whole batch with 429, and nothing is registered. Picking the same episodes one by one with "Choose Episodes" works.

Approach

App downloads are managed entries. Original-quality managed entries, and prepared ones whose file is already ready, are created as ready and do not count as active until the app reports progress, but the concurrent check counted every new entry in the batch. Now only new entries that start preparing count toward the concurrent cap, the same rule prepared replacements and series monitors already use. The apps queue the transfers of ready entries.

Web (ephemeral) downloads keep both checks. A season requested at a transcoded quality still counts each episode that needs an encode, so it is refused when those episodes outnumber the free slots. The period quota still covers every new managed row.

Validation

  • Go: internal/downloads tests pass against a migrated Postgres, including a new regression test, which is added to scripts/ci/db-contracts.txt so the DB job runs it. With the cap of 2 already full, a 4-episode original batch registers, a 2-episode transcoded batch is refused without inserting rows or queueing an encode, and a batch over the period quota is refused without inserting a row. The test fails on main without the fix. TestManagedCreateAbsenceRacePostgres times out locally with and without this change.
  • Lint: make lint-changed reports 0 issues.
  • iOS simulator (current silo-apple main) and Android emulator (current silo-android main) against a local stack with a 6-episode season and a limit of 2:
    • Before: iOS showed "Download Failed — concurrent download limit reached", Android got 429, and no rows were created.
    • After: both registered all 6 episodes and finished downloading them, and iOS never ran more than 2 transfers at a time.
  • TestAdminSubtitleListPageDB and TestAdminResourceCapabilitiesAndScope fail locally on unmodified main as well; they are unrelated to this change.

Risks

  • While an app downloads a season, it can report several episodes as downloading at once. Those rows count toward the concurrent limit and can briefly block the same user's web or transcoded downloads until they finish. "Choose Episodes" already caused this before this change.
  • No API shape change and no client change needed. jellycompat has no download batch path.

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.159.2 (review); Maestro (simulator QA)
  • Model(s): claude-opus-5-5[1m]; gpt-6.1-sol (review); gpt-6-astra (review)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: Claude Code's code-review and the Codex CLI reviewer (gpt-6.1-sol and gpt-6-astra, medium effort) each reviewed the complete diff. None reported a defect. Both Codex reviewers noted that managed rows count as active once an app reports them as downloading. That behavior predates this change and is listed under Risks.

Note

Fix managed download batches to queue ready entries over the concurrent cap

  • Changes downloads.Service.ensureManagedDecisions so new entries count as activating only when they need an artifact that is not already ready. Original entries and entries backed by ready prepared artifacts can now register when the concurrent cap is full
  • Entries that must begin preparation still require free concurrent capacity. Every new entry still counts toward the period quota
  • Updates the rate_limited problem-code docs in downloads-api.md to match
  • Adds TestManagedBatchOverConcurrentCapDB in service_quota_test.go and registers it in db-contracts.txt
  • Behavioral Change: rate_limited is no longer returned for ready entries when the concurrent cap is full; clients relying on that code for those cases will see them accepted instead

Macroscope summarized 1c9fb79.

@kody-ai

kody-ai Bot commented Sep 30, 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 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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

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: aa6c9762-b446-4630-871d-b3e33ad71980

📥 Commits

Reviewing files that changed from the base of the PR and between 17eced4 and e188d75.

📒 Files selected for processing (4)
  • docs/downloads-api.md
  • internal/downloads/limiter.go
  • internal/downloads/service.go
  • internal/downloads/service_quota_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

Managed original batches now use the period quota without applying the concurrent download cap. The standard limiter check still enforces both limits. The API documentation and tests reflect the managed-download behavior.

Changes

Managed download quotas

Layer / File(s) Summary
Separate period and concurrent checks
internal/downloads/limiter.go
QuantityLimiter now provides CheckPeriod. Check retains concurrent-limit enforcement, and the shared check can skip it.
Apply period-only checks to managed batches
internal/downloads/service.go, internal/downloads/service_quota_test.go, docs/downloads-api.md
ensureManaged uses CheckPeriod for new managed original entries. A test checks registration above the concurrent cap and rejection above the period quota. The API error description documents the exception.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: quick104

Merge Risk: ⚪ Minimal · up to e188d

Managed original batches can register above the concurrent cap while retaining period quotas. Other download paths retain both limits. No actionable merge-blocking risk is identified; merge after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to e188d

Managed original downloads retain period-quota and ownership checks, while larger batches become eligible for registration. The concurrency restriction was not previously a reliable limit on actual managed transfers: clients could already register episodes individually before starting them. No new cross-user access or period-quota bypass was demonstrated, but queueing across all supported clients remains unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The changed capability concerns registration volume for a permitted downloader's managed originals and potential load on shared delivery resources. Inspected ownership and content checks continue to constrain accessible media; the change does not establish additional cross-account authority or new artifact-preparation privileges.

Security Findings and Attack Paths

  • inferred — A non-cooperative permitted downloader could already accumulate ready entries through small registrations and request parallel transfers without reporting progress. This predates the PR: ready entries did not consume active quota, and managed serving did not enforce that quota. Larger registrations simplify this workflow but do not demonstrate a newly introduced maximum-concurrency bypass.

Trust Boundaries and Controls

  • observed — Managed file resolution requires the user/profile/device tuple, rejects revoked entries, and rechecks content and file-level access. Status reporting accepts only downloading or completed and updates rows within the same ownership tuple. These controls are distinct from cooperative client queueing.

Resilience and Maintainability Implications

  • observed — Configured bandwidth controls remain independent of registration quota: local serving uses shared per-user and server token buckets. The service disallows proxy delivery when bandwidth caps are configured, preserving that existing containment policy rather than replacing it with client queueing.

Hardening Proposals

  • proposed — If the concurrent setting is intended as an adversarial resource-isolation guarantee for managed transfers, enforce server-owned transfer slots at byte-serving admission, with interruption-safe release and recovery, separately from ready-entry registration. This would strengthen a pre-existing cooperative boundary rather than fix a demonstrated new vulnerability.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Issue [#1703] requires series batches larger than the concurrent limit to be accepted. ensureManaged now calls CheckPeriod, so the batch size does not trigger ErrConcurrentLimitReached. Check …
Out of Scope Changes check ✅ Passed The changes stay within issue [#1703]. The limiter helper supports the required quota distinction, service.go applies it to managed original entries, the API documentation records the behavior, and …
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. (1 skipped: 1 …
Title check ✅ Passed The title clearly summarizes the main change: allowing season and series downloads to be queued when they exceed the concurrent limit.
Description check ✅ Passed The description explains the problem, the quota-check change, its scope, and validation. It is directly related to the changeset.
✨ 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.

@macroscopeapp

macroscopeapp Bot commented Sep 30, 2026

Copy link
Copy Markdown

Validation tasks: should point to the limit cases affected by this change. The PR changes enforcement of download.max_concurrent_per_user for managed originals, while #1168 C1 covers download permissions and bandwidth/storage limits. The direct server limit case is #1217 C1, and #1218 C1 verifies configured limits’ effective behavior with the server task. Both are currently Not run, so there is no recorded result to invalidate. Suggested line: Validation tasks: changes #1217 C1; changes #1218 C1.

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

Posted via Macroscope — v1 validation impact

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

Code review of e188d75. The fix doesn't carry over to current main as written. #1880 moved this limiter check into ensureManagedDecisions, where a managed season or series batch can now include episodes that need an encode. Those rows start as preparing and count as active. The PR conflicts with main in limiter.go, service.go, and service_quota_test.go, and #1703 is still present on main: this PR's test, applied to main and run against a migrated Postgres, fails with concurrent download limit reached. The inline comments cover the rebase fix, the client queueing assumption, and test coverage.

Validation tasks (needs your call): #1217 C1, #1218 C1, and #1168 C1 are all Not run. CLAUDE.md asks this line to name passed cases the change could reach, and none are passed, so I'd write Validation tasks: none and name #1217 C1 and #1218 C1 in prose as the cases to watch when they run. This differs from the Macroscope comment above, which keeps them on the line.

Checked and ruled out: the /api/v1 behavior change (an allowed bridge fix, since v1 and v2 share the service), unlimited registrations and rows stuck in downloading (both predate this PR), and the downloads-api.md row (still accurate after a correct rebase).

AI disclosure: review by claude-opus-5-5 in Claude Code via T3 Code (/silo code-review), posted at a maintainer's request.

Comment thread internal/downloads/service.go Outdated
if err := s.limiter.Check(ctx, userID, len(newIdx)); err != nil {
// Managed originals register as 'ready' and never count as active, so
// only the period quota applies; the client queues the transfers.
if err := s.limiter.CheckPeriod(ctx, userID, len(newIdx)); err != nil {

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.

High: the fix can't land on current main, and neither side of the conflict is correct.

On main (#1880), ensureManaged is a one-line wrapper. The check now sits in ensureManagedDecisions: activating := len(newIdx), then s.limiter.CheckCounts(ctx, userID, activating, len(newIdx)). A season or series batch there can carry a quality decision per episode.

Suggested repair on main: count only the new entries that will start active, the way the replacement loop and paceToSlots already do, and keep CheckCounts:

activating := 0
for _, i := range newIdx {
	d := decisions[i]
	if d.RequiresArtifact && !s.artifacts.readyArtifact(ctx, items[i].file, d.DeliveryFormat, d.PrepareTarget) {
		activating++
	}
}
// existing loop: activating++ for prepared replacements where replacementAddsActive
if err := s.limiter.CheckCounts(ctx, userID, activating, len(newIdx)); err != nil {

With that, CheckPeriod and check(..., concurrent bool) aren't needed. Drop the comment above this line too: on main this check also covers preparing rows, which do count as active.

Needs your call: even with that fix, an interactive season at a transcoded quality whose unready episodes outnumber the free slots is still rejected as a whole, while series monitors pace the same case through FreeConcurrentSlots. Either pace interactive batches too, or scope the title and docs to original quality.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Rebased onto main as 1c9fb79 (force-pushed). ensureManagedDecisions now counts only new entries that start preparing (needs an artifact that is not ready yet) and keeps CheckCounts; CheckPeriod and the old comment are gone. The interactive-pacing question is still open.

Comment thread internal/downloads/service.go Outdated
if err := s.repo.WithUserQuotaLock(ctx, userID, func(ctx context.Context) error {
if err := s.limiter.Check(ctx, userID, len(newIdx)); err != nil {
// Managed originals register as 'ready' and never count as active, so
// only the period quota applies; the client queues the transfers.

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.

Medium (needs your call): Android doesn't queue transfers, so the reason for skipping the cap holds only for iOS.

silo-apple limits transfers (maxConcurrentTransfers in DownloadManager.swift). silo-android enqueues one unique WorkManager worker per download (enqueueUniqueWork(tagFor(downloadId), ...) in DownloadWorker.kt) with no app-level limit, and each worker reports downloading when it starts. With a cap of 3, a 10-episode season on Android can put all 10 rows in downloading. That user's web and transcoded downloads then get 429 until the season finishes. The Risks section describes a brief overlap; on Android it's the normal path. I read silo-android at 7ddec0401 and didn't measure how much WorkManager's own scheduling limits parallel workers.

Options: add a transfer limit to the Android app (a follow-up in silo-android), or keep this change and say in Risks that Android runs season transfers in parallel.

// TestManagedBatchLargerThanConcurrentCapRegisters pins that a managed season
// or series batch larger than the concurrent cap registers every episode: the
// rows are 'ready' and the client queues the transfers. The period quota still
// rejects a batch that would exceed it.

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.

Medium: this regression test won't run in CI, and the risky side of the rebase has no test.

  • It needs SILO_TEST_DATABASE_URL. make test-go runs without a database, so the test skips, and the DB job runs only tests listed in scripts/ci/db-pins.txt and scripts/ci/db-contracts.txt. Add it to main's scripts/ci/db-contracts.txt next to the other downloads entries.
  • No test sends new episodes that need an encode through ensureManagedDecisions over the cap. The existing tests cover replacements, createArtifactDownload, and the paced monitor path, and all of them pass with a resolution that drops the concurrent check for new preparing rows. A mixed-batch test would catch that: originals over the cap register, and new episodes at a transcoded quality over the cap get ErrConcurrentLimitReached.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 1c9fb79: TestManagedBatchOverConcurrentCapDB is listed in scripts/ci/db-contracts.txt, and it sends two new episodes at 5 Mbps through ensureManagedDecisions with the cap full and expects ErrConcurrentLimitReached, no inserted rows, and no queued encode.

if err != nil {
t.Fatalf("season batch over the concurrent cap: %v", err)
}
if len(rows) != 4 {

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.

Low: this half also passes on the old code.

Items 0–3 already exist, so only item 4 is new. The pre-fix Check passes the concurrent check (0 active + 1 ≤ 2) and fails the period check (4 + 1 > 4), so this pins only that a period check still runs. Two additions would make the test stricter: seed queued or downloading rows at the cap before the first call, which catches a resolution that brings the concurrent check back only when the user already has active rows; and assert that the rejected call didn't insert a fifth row.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 1c9fb79: the test seeds a queued and a downloading row at the cap of 2 before the original batch, and checks that the period-quota rejection inserts no row.

Comment thread internal/downloads/limiter.go Outdated
// CheckPeriod verifies only the per-period quota. Managed original entries use
// it: they register as 'ready' and the client queues their transfers, so the
// concurrent cap must not reject a season or series larger than the cap.
func (l *QuantityLimiter) CheckPeriod(ctx context.Context, userID int, batchSize int) error {

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.

Low (cleanup): CheckPeriod duplicates CheckCounts on main.

Main already has CheckCounts(ctx, userID, activating, created), and Check delegates to it, so CheckPeriod(n) is CheckCounts(ctx, userID, 0, n). A boolean also can't express a batch where some rows start ready and others preparing, and these lines conflict with main. With the repair in the service.go comment, this file needs no change.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed; after the rebase in 1c9fb79 limiter.go is unchanged and the batch uses CheckCounts.

… limit

A managed season or series batch was refused whenever it had more new
episodes than the per-user concurrent limit, because every new entry counted
as activating. Original entries, and prepared ones whose file is already
ready, register ready and the app queues their transfers, so only new entries
that start preparing now count toward the concurrent cap, the way prepared
replacements already did. The period quota still covers every new entry.
@Rhainland
Rhainland force-pushed the fix/season-download-queue-over-limit branch from e188d75 to 1c9fb79 Compare October 5, 2026 08:47
@silo-kody

silo-kody Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌
⚠️ 1 Kody Rule(s) were not evaluated

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

  • Preserve optional store capabilities through production wrappers

@Rhainland

Copy link
Copy Markdown
Contributor Author

Validation tasks line from the review summary: changed to Validation tasks: none, with #1217 C1 and #1218 C1 named in parentheses as the cases to watch, since neither has a recorded result.

@Quick104
Quick104 merged commit e4aaab2 into Silo-Server:main Oct 5, 2026
21 of 23 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.

[bug] Download series always fails with 429 when the series has more episodes than the concurrent download limit

2 participants