Repository navigation
fix(downloads): queue season and series downloads over the concurrent limit - #1713
Conversation
Code Review Completed! 🔥The code review was successfully completed based on your current configurations. Kody Guide: Usage and ConfigurationInteracting with Kody
Providing Context (Files & MCPs)Add these hints in your PR description (or a comment) to unlock deeper checks:
Current Kody ConfigurationReview OptionsThe following review options are enabled or disabled:
|
|
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 configurationConfiguration used: Organization UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (4)
Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review. 📝 WalkthroughWalkthroughManaged 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. ChangesManaged download quotas
Priority: ➖ Normal Estimated code review effort: 2 (Simple) | ~10 minutes Change: Bug fix · Severity of issue fixed: Medium Suggested reviewers: Merge Risk: ⚪ Minimal · up to 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 ReviewSecurity architecture risk: 🔵 Low · up to 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 Security review detailsSecurity Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
|
Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed. Posted via Macroscope — v1 validation impact |
Quick104
left a comment
There was a problem hiding this comment.
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.
| 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 { |
There was a problem hiding this comment.
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.
- Keep main's side: [bug] Download series always fails with 429 when the series has more episodes than the concurrent download limit #1703 stays. This PR's test fails on main with
concurrent download limit reached. - Carry
CheckPeriod(orCheckCounts(ctx, userID, 0, len(newIdx))) over: a season requested at a transcoded quality skips the concurrent cap. Each new episode's row starts aspreparingand queues an encode. With a cap of 2 and both slots in use, a 10-episode season at 5 Mbps leaves the user at 12 active downloads with 10 encodes queued.
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.
There was a problem hiding this comment.
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.
| 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. |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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-goruns without a database, so the test skips, and the DB job runs only tests listed inscripts/ci/db-pins.txtandscripts/ci/db-contracts.txt. Add it to main'sscripts/ci/db-contracts.txtnext to the other downloads entries. - No test sends new episodes that need an encode through
ensureManagedDecisionsover 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 newpreparingrows. A mixed-batch test would catch that: originals over the cap register, and new episodes at a transcoded quality over the cap getErrConcurrentLimitReached.
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| // 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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
e188d75 to
1c9fb79
Compare
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
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 with429, 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
readyand 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 startpreparingcount toward the concurrent cap, the same rule prepared replacements and series monitors already use. The apps queue the transfers ofreadyentries.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
internal/downloadstests pass against a migrated Postgres, including a new regression test, which is added toscripts/ci/db-contracts.txtso 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 onmainwithout the fix.TestManagedCreateAbsenceRacePostgrestimes out locally with and without this change.make lint-changedreports 0 issues.silo-applemain) and Android emulator (currentsilo-androidmain) against a local stack with a 6-episode season and a limit of 2:429, and no rows were created.TestAdminSubtitleListPageDBandTestAdminResourceCapabilitiesAndScopefail locally on unmodifiedmainas well; they are unrelated to this change.Risks
downloadingat 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.Checklist
AI Disclosure
downloading. That behavior predates this change and is listed under Risks.Note
Fix managed download batches to queue ready entries over the concurrent cap
downloads.Service.ensureManagedDecisionsso 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 fullrate_limitedproblem-code docs in downloads-api.md to matchTestManagedBatchOverConcurrentCapDBin service_quota_test.go and registers it in db-contracts.txtrate_limitedis no longer returned for ready entries when the concurrent cap is full; clients relying on that code for those cases will see them accepted insteadMacroscope summarized 1c9fb79.