Skip to content

feat(requests): add media request system - #6

Closed
Quick104 wants to merge 0 commit into
mainfrom
t3code/discover-studios-networks-genres
Closed

Quick104 wants to merge 0 commit into
mainfrom
t3code/discover-studios-networks-genres

Conversation

@Quick104

@Quick104 Quick104 commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Introduce an end-to-end media requests system: TMDB-backed search/discovery/detail APIs, a quota-aware request service, Radarr/Sonarr fulfillment, and a reconcile-requests background task.
  • Build the user-facing Requests experience: /requests discovery + search + "Yours" tabs, request detail page, and admin queue/settings/limits surfaces.
  • Layer curated Studios, Networks, and Genres discovery on top of the request stack using duotone TMDB logos and fixed logo paths instead of per-request logo lookups.

Test plan

  • go test ./internal/requests ./internal/metadata/tmdb ./internal/api/handlers
  • Manually exercised /requests: verified discovery carousels render, browse routes for studios/networks/genres work, and request cards show the correct state ribbons and dimming.

Made with Cursor


Note

High Risk
Touches authenticated APIs, admin settings for external arr API keys, fulfillment/reconciliation, and a large new domain surface area with quota and request-state rules.

Overview
Adds a media request system end-to-end: new internal/requests service and HTTP handlers for TMDB search/discovery/detail, creating and listing requests, admin approve/decline/retry, settings, per-user limits, and Radarr/Sonarr integrations (including sensitive setting keys). TMDB client gains search, discovery sections, paginated discover with companies/networks, media detail, and company/network lookups. API router wires profile /requests/* and admin request routes; server startup registers a reconcile-requests background task.

Brand discovery on top of requests: bundled studios/networks/genres, list + browse APIs, and browse routes ordered before generic discover paths. Web adds Requests, RequestBrowse, detail routes, brand carousels, and clears request queries on profile change.

Repo hygiene: pre-commit hook and make verify-local-paths / install-hooks to block local filesystem paths in commits; AGENTS.md documents the same for superpowers docs. Large specs/plans describe the request system and studios/networks/genres design (documentation only in this diff).

Reviewed by Cursor Bugbot for commit 30396df. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • New Features

    • Full media request system: discovery/search/detail, create requests, lifecycle (pending→approved→queued→downloading→completed).
    • Browse-by-brand carousels and browse pages for studios, networks, and genres.
    • Radarr & Sonarr fulfillment integrations and background reconciliation worker to update request status.
    • Admin Requests UI: queue, global settings, integrations, per-user limits; API keys now hidden from settings responses.
  • Style/UX

    • New Request pages/components and downloading shimmer; clears request cache on profile change/logout.
  • Documentation

    • Detailed specs and implementation plans for the request system and browse design.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4032d727-ae8e-4cbd-be84-1837b40834e6

📥 Commits

Reviewing files that changed from the base of the PR and between fc237f4 and 30396df.

📒 Files selected for processing (4)
  • .githooks/pre-commit
  • AGENTS.md
  • Makefile
  • scripts/check-local-path-leaks.sh

📝 Walkthrough

Walkthrough

Adds a full media request feature: DB migrations, domain types/store/errors, TMDB client and normalization, Radarr/Sonarr adapters, repository and service orchestration (create/reconcile/approve/decline/retry), HTTP handlers/router, background reconcile task wiring, web types/hooks/pages/components, and documentation/tests.

Changes

Media Requests end-to-end feature

Layer / File(s) Summary
Schema and migrations
migrations/139_media_requests.*.sql
Creates tables for settings, per-user limits, integrations, media requests, and events; adds indexes and down migration.
Core domain contracts & store
internal/requests/types.go, internal/requests/errors.go, internal/requests/store.go
Defines enums, data shapes, sentinel errors (QuotaError), and the Store/CreateRequestRecord contract.
TMDB client and types/tests
internal/metadata/tmdb/*
Adds TMDB search/discover/page/detail APIs, normalization to MediaPage/MediaDetail, extended discover params, and tests.
Catalog presence
internal/requests/presence.go
Resolves availability of TMDB IDs via catalog repository.
Service orchestration + tests
internal/requests/service.go, internal/requests/service_test.go
Implements search/discover/detail, create with policy/quota/auto-approve, admin actions, reconciliation, enrichment, integration management, and many tests.
Discover brand/bundle + tests
internal/requests/discover_*.go, internal/requests/discover_bundle_test.go
Adds bundled studios/networks/genres, duotone/logo helpers, list and browse flows with sort/media-type normalization and tests.
ARR client & helpers
internal/requests/arrclient/*
Provides arrclient HTTP wrapper, Bool/String option helpers, and queue evaluation used by Radarr/Sonarr adapters.
Radarr integration + tests
internal/requests/radarr/*
Movie submission, queue/status mapping, integration options retrieval, and tests.
Sonarr integration + tests
internal/requests/sonarr/*
Series submission, queue/status mapping, integration options retrieval, and tests.
Repository implementation
internal/requests/repository.go
Persists settings/limits/requests/events/integrations and handles transactional state transitions and scanning helpers.
Service tests/fakes
internal/requests/service_test.go
In-memory fakes and tests covering create, search enrichment, reconciliation, bundle/list/browse behavior.
API handlers and router
internal/api/handlers/requests.go, internal/api/router.go, internal/api/handlers/admin.go, internal/api/handlers/requests_test.go
Exposes user/admin endpoints, maps domain errors to HTTP responses, validates inputs, shapes integration responses, wires routes, and masks API-key settings.
Background task and wiring
internal/taskmanager/tasks/reconcile_requests.go, cmd/silo/main.go
Adds ReconcileRequestsTask, RequestReconciler interface, and worker startup wiring registering the reconcile task (limit default 100) with secret/adapter resolution.
Web API/types/hooks
web/src/api/types.ts, web/src/hooks/queries/*
Adds TypeScript API models, React Query keys, and hooks/mutations for discovery/browse/search/detail/create and admin integrations/settings/limits.
Web UI/pages/components/styles
web/src/App.tsx, web/src/pages/*, web/src/components/*, web/src/app.css
Adds Requests, Browse, Detail, AdminRequests pages; BrandCard/BrandCarousel/RequestPosterCard components; sidebar links; downloading shimmer and related styles.
Documentation/specs & ops
docs/superpowers/specs/*, docs/superpowers/plans/*, Makefile, scripts/check-local-path-leaks.sh, .githooks/pre-commit, AGENTS.md
Adds request system spec, discover-by-brand design, phased implementation plan, repo guidelines, Makefile targets, and a script + pre-commit hook to detect local path leaks.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Poem

A rabbit taps with gentle cheer,
New requests bloom far and near—
TMDB winds and adapters hum,
Queues reconcile until they're done.
Hop, approve, and ship with style. 🐇✨

✨ 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 t3code/discover-studios-networks-genres

@Quick104 Quick104 changed the title feat(requests): discover studios, networks, and genres feat(requests): add media request system May 24, 2026
GradientFrom string `json:"gradient_from,omitempty"`
GradientTo string `json:"gradient_to,omitempty"`
SeriesSupported bool `json:"series_supported,omitempty"`
}

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.

Missing BrandColor field in brand card structs

Medium Severity

The DiscoverBrandCard struct is missing a BrandColor field, and the BundledStudio/BundledNetwork structs replaced BrandColor with LogoPath instead of keeping both. The committed spec (same PR) defines brand_color as a required JSON field on brand cards, and the committed plan shows frontend code using card.brand_color as the card background color. Without it, all studio/network cards will render with an identical fallback gray background instead of their distinctive brand colors (Marvel red, Disney blue, etc.). The LogoPath serves a different purpose (the duotone logo image) and doesn't replace the need for a background color.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 27d94fe01e8e1dd3f13606345b9b5c61172e24ab. Configure here.

@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: 9

🧹 Nitpick comments (2)
web/src/hooks/queries/requests.ts (1)

1-1: ⚡ Quick win

Rename this hooks module to match the required useThing.ts pattern.

This file exports custom React hooks, but web/src/hooks/queries/requests.ts does not follow the hook filename convention. Please rename it (for example, useRequests.ts) and update imports.

As per coding guidelines, web/src/hooks/**/*.ts: Use useThing.ts naming convention for custom React hooks.

🤖 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 `@web/src/hooks/queries/requests.ts` at line 1, Rename the module file from
requests.ts to follow the hook naming convention (e.g., useRequests.ts), keep
the exported hook function names unchanged, and update every import site to
point to the new filename (including any barrel/index exports, tests, and
components that import these hooks); also update any re-exports in
hooks/index.ts or similar so the hook is discoverable under the new filename and
run the build/tests to verify no broken imports remain.
internal/taskmanager/tasks/reconcile_requests.go (1)

54-56: ⚡ Quick win

Handle result serialization errors explicitly.

json.Marshal failures are currently dropped, so task output can disappear without signal.

Proposed change
-	if data, err := json.Marshal(result); err == nil {
-		progress.SetResultData(data)
-	}
+	data, err := json.Marshal(result)
+	if err != nil {
+		return fmt.Errorf("marshal reconcile result: %w", err)
+	}
+	progress.SetResultData(data)
🤖 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/taskmanager/tasks/reconcile_requests.go` around lines 54 - 56, The
json.Marshal(result) error is currently ignored; update the code around
json.Marshal(result) so that if err != nil you handle it explicitly (e.g., log
the error using the task logger, mark the task/progress as failed or set an
error result, and return or propagate the error) instead of silently dropping
it; keep the successful path that calls progress.SetResultData(data) when
marshalling succeeds and reference the existing json.Marshal(result) and
progress.SetResultData calls when making the change.
🤖 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
`@docs/superpowers/specs/2026-05-24-discover-studios-networks-genres-design.md`:
- Around line 173-177: The markdown code fences for the HTTP endpoints are
missing language identifiers (MD040); update the three fenced blocks that
contain the endpoint lists (the blocks showing GET
/api/v1/requests/discover/studios, GET /api/v1/requests/discover/networks, GET
/api/v1/requests/discover/genres and the two other similar blocks that list
browse endpoints) by adding appropriate language tags (e.g., ```http for the
full GET request examples and ```text for simple path listings) so each fence
includes a language identifier.

In `@internal/api/handlers/requests.go`:
- Around line 313-315: The JSON decode error for decline requests is ignored;
capture the decoder error when calling json.NewDecoder(r.Body).Decode(&body) and
if err is non-nil and not io.EOF, respond with HTTP 400 and stop processing so
malformed JSON is rejected while allowing an empty body/EOF. Update the handler
code that references r.Body and body (the decode block in requests.go) to check
err != nil && err != io.EOF, return a 400 (e.g., using http.Error or writing a
JSON error) and ensure io is imported.
- Around line 395-403: The loop in the PUT batch handler calls
h.service.UpsertIntegration per item and returns on first error, causing partial
persistence; change this to an atomic operation by delegating the whole slice to
a transactional service call (e.g., implement and call
h.service.UpsertIntegrations(ctx, viewer, body.Integrations) or wrap the loop in
a service-managed transaction) so either all integrations are applied or none
are; on error, ensure you do not persist partial results and still return the
appropriate writeRequestServiceError response. Use the existing symbols
body.Integrations, h.service.UpsertIntegration as reference when adding the new
transactional method or wrapping logic so callers and tests can be updated
accordingly.

In `@internal/requests/presence.go`:
- Around line 27-35: After filtering tmdbIDs into ids, add a guard that if
len(ids) == 0 you skip calling p.items.LookupTMDBIDs and return immediately with
the appropriate empty result (e.g., empty slice/map and nil error) instead of
invoking LookupTMDBIDs; update the code around the ids variable and the
LookupTMDBIDs call to short-circuit on empty ids to avoid unnecessary DB work
and errors.

In `@internal/requests/repository.go`:
- Around line 349-451: These methods (SetStatus, MarkQueued, SetOutcome) update
the same media_requests row without any lock or precondition, allowing
concurrent writers to clobber state; wrap the update in a row lock and
optionally validate the current state: begin the same transaction as created
(tx), run a SELECT id, status, outcome FROM media_requests WHERE id = $1 FOR
UPDATE using tx.QueryRow to lock the row and read current values (use the same
id param), validate or assert expected current status/outcome if needed, then
perform the UPDATE via tx (e.g., tx.QueryRow) and continue calling
r.recordEvent(ctx, tx, ...) and tx.Commit(ctx) as before; update references:
SetStatus, MarkQueued, SetOutcome, scanRequest, and recordEvent so the lock/read
and validation happen inside the transaction before the UPDATE.
- Around line 657-659: The current code swallows json.Unmarshal errors when
decoding optionsRaw into integration.Options; change the block in repository.go
so that you capture the error returned by json.Unmarshal(optionsRaw,
&integration.Options) and handle it instead of discarding it—either return the
error from the enclosing function (propagate) or log and wrap it with context
(including identifiers for the affected integration) so corrupted persisted
payloads aren’t silently replaced by {}. Ensure you reference optionsRaw and
integration.Options and update the function signature/return path as needed to
propagate the unmarshalling error.

In `@internal/requests/service.go`:
- Around line 242-252: CreateRequest currently calls service backends (e.g.,
s.store, s.tmdb, lookupAvailable) without the configuration guard used in
Search/Discover/GetDetail, which can cause nil dereference panics on a
misconfigured Service; add the same configuration check at the start of
CreateRequest (validate that the service is configured and required subsystems
like s.store and s.tmdb are non-nil or call the existing ensure-config helper
used elsewhere), and if not configured return the standard configuration error
(e.g., ErrServiceNotConfigured) instead of proceeding to call s.store/s.tmdb or
lookupAvailable.

In `@internal/requests/sonarr/client.go`:
- Around line 155-157: The code currently returns matches[0] whenever matches is
non-empty even if none have the requested TVDB ID, which can submit the wrong
series; update the logic to scan the matches slice for an item whose TVDBID
(match.TVDBID) exactly equals the requested TVDB ID and return that match, and
only if no exact match is found return a not-found error (do not fall back to
matches[0]); modify the block around the matches variable in client.go to
perform this exact-match check and return a clear error (e.g., ErrSeriesNotFound
or a descriptive error) when no exact TVDBID match exists.

In `@web/src/pages/Requests.tsx`:
- Around line 200-201: The pending-card logic currently only keys off
createRequest.variables?.tmdb_id (passed as pendingTMDBID) so movies and TV can
collide; update the component props and usage to also pass
createRequest.variables?.media_type (e.g., pendingMediaType) and change the
pending detection to require both tmdb_id and media_type match while still using
createRequest.isPending for isSubmitting; apply the same change to the other two
occurrences where createRequest.variables?.tmdb_id and createRequest.isPending
are used so all pending-card checks compare both tmdb_id and media_type.

---

Nitpick comments:
In `@internal/taskmanager/tasks/reconcile_requests.go`:
- Around line 54-56: The json.Marshal(result) error is currently ignored; update
the code around json.Marshal(result) so that if err != nil you handle it
explicitly (e.g., log the error using the task logger, mark the task/progress as
failed or set an error result, and return or propagate the error) instead of
silently dropping it; keep the successful path that calls
progress.SetResultData(data) when marshalling succeeds and reference the
existing json.Marshal(result) and progress.SetResultData calls when making the
change.

In `@web/src/hooks/queries/requests.ts`:
- Line 1: Rename the module file from requests.ts to follow the hook naming
convention (e.g., useRequests.ts), keep the exported hook function names
unchanged, and update every import site to point to the new filename (including
any barrel/index exports, tests, and components that import these hooks); also
update any re-exports in hooks/index.ts or similar so the hook is discoverable
under the new filename and run the build/tests to verify no broken imports
remain.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: f20c08c0-6d96-4bc5-9c68-c648c4dc56d5

📥 Commits

Reviewing files that changed from the base of the PR and between 95628f95429b221662f324c9107cea62b63bf842 and 27d94fe01e8e1dd3f13606345b9b5c61172e24ab.

📒 Files selected for processing (48)
  • cmd/silo/main.go
  • docs/superpowers/plans/2026-05-24-discover-studios-networks-genres.md
  • docs/superpowers/plans/request-system-implementation.md
  • docs/superpowers/specs/2026-05-24-discover-studios-networks-genres-design.md
  • docs/superpowers/specs/request-system.md
  • internal/api/handlers/admin.go
  • internal/api/handlers/requests.go
  • internal/api/handlers/requests_test.go
  • internal/api/router.go
  • internal/metadata/tmdb/client.go
  • internal/metadata/tmdb/client_test.go
  • internal/metadata/tmdb/types.go
  • internal/requests/arrclient/client.go
  • internal/requests/arrclient/options.go
  • internal/requests/arrclient/queue.go
  • internal/requests/discover_brand.go
  • internal/requests/discover_bundle.go
  • internal/requests/discover_bundle_test.go
  • internal/requests/errors.go
  • internal/requests/presence.go
  • internal/requests/radarr/client.go
  • internal/requests/radarr/client_test.go
  • internal/requests/repository.go
  • internal/requests/service.go
  • internal/requests/service_test.go
  • internal/requests/sonarr/client.go
  • internal/requests/sonarr/client_test.go
  • internal/requests/store.go
  • internal/requests/types.go
  • internal/taskmanager/tasks/reconcile_requests.go
  • migrations/139_media_requests.down.sql
  • migrations/139_media_requests.up.sql
  • web/src/App.tsx
  • web/src/api/types.ts
  • web/src/app.css
  • web/src/components/AdminSidebar.tsx
  • web/src/components/AppSidebar.tsx
  • web/src/components/BrandCard.tsx
  • web/src/components/BrandCarousel.tsx
  • web/src/components/RequestPosterCard.tsx
  • web/src/hooks/queries/keys.ts
  • web/src/hooks/queries/requests.ts
  • web/src/lib/documentTitle.ts
  • web/src/lib/mediaRequests.ts
  • web/src/pages/AdminRequests.tsx
  • web/src/pages/RequestBrowse.tsx
  • web/src/pages/RequestDetail.tsx
  • web/src/pages/Requests.tsx

Comment on lines +173 to +177
```
GET /api/v1/requests/discover/studios
GET /api/v1/requests/discover/networks
GET /api/v1/requests/discover/genres
```

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add language identifiers to fenced blocks to satisfy markdown lint.

These code fences omit a language tag and are flagged by MD040 (Line 173, Line 185, Line 250).

Proposed fix
-```
+```http
 GET /api/v1/requests/discover/studios
 GET /api/v1/requests/discover/networks
 GET /api/v1/requests/discover/genres

- +http
GET /api/v1/requests/discover/browse/studio/{slug}?page=1&sort=popularity
GET /api/v1/requests/discover/browse/network/{slug}?page=1&sort=popularity
GET /api/v1/requests/discover/browse/genre/{slug}?media_type=movie&page=1&sort=popularity


-```
+```text
/requests/browse/studio/:slug
/requests/browse/network/:slug
/requests/browse/genre/:slug
</details>


Also applies to: 185-189, 250-254

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.22.1)</summary>

[warning] 173-173: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

</details>

</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

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

In @docs/superpowers/specs/2026-05-24-discover-studios-networks-genres-design.md
around lines 173 - 177, The markdown code fences for the HTTP endpoints are
missing language identifiers (MD040); update the three fenced blocks that
contain the endpoint lists (the blocks showing GET
/api/v1/requests/discover/studios, GET /api/v1/requests/discover/networks, GET
/api/v1/requests/discover/genres and the two other similar blocks that list
browse endpoints) by adding appropriate language tags (e.g., http for the full GET request examples and text for simple path listings) so each fence
includes a language identifier.


</details>

<!-- fingerprinting:phantom:triton:hawk -->

<!-- This is an auto-generated comment by CodeRabbit -->

Comment on lines +313 to +315
if r.Body != nil {
_ = json.NewDecoder(r.Body).Decode(&body)
}

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Malformed JSON is silently accepted in decline requests.

The decode error is ignored, so invalid JSON can still execute a decline with an empty reason. Return 400 for malformed payloads (while still allowing empty body/EOF).

✅ Minimal fix
 import (
 	"context"
 	"encoding/json"
 	"errors"
+	"io"
 	"net/http"
 	"strconv"
 	"strings"
 	"time"
@@
 	var body struct {
 		Reason string `json:"reason"`
 	}
 	if r.Body != nil {
-		_ = json.NewDecoder(r.Body).Decode(&body)
+		if err := json.NewDecoder(r.Body).Decode(&body); err != nil && !errors.Is(err, io.EOF) {
+			writeError(w, http.StatusBadRequest, "bad_request", "Invalid request body")
+			return
+		}
 	}
📝 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 r.Body != nil {
_ = json.NewDecoder(r.Body).Decode(&body)
}
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"strings"
"time"
)
var body struct {
Reason string `json:"reason"`
}
if r.Body != nil {
if err := json.NewDecoder(r.Body).Decode(&body); err != nil && !errors.Is(err, io.EOF) {
writeError(w, http.StatusBadRequest, "bad_request", "Invalid request body")
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/requests.go` around lines 313 - 315, The JSON decode
error for decline requests is ignored; capture the decoder error when calling
json.NewDecoder(r.Body).Decode(&body) and if err is non-nil and not io.EOF,
respond with HTTP 400 and stop processing so malformed JSON is rejected while
allowing an empty body/EOF. Update the handler code that references r.Body and
body (the decode block in requests.go) to check err != nil && err != io.EOF,
return a 400 (e.g., using http.Error or writing a JSON error) and ensure io is
imported.

Comment on lines +395 to +403
updated := make([]mediarequests.Integration, 0, len(body.Integrations))
for _, integration := range body.Integrations {
result, err := h.service.UpsertIntegration(r.Context(), viewer, integration)
if err != nil {
writeRequestServiceError(w, err)
return
}
updated = append(updated, *result)
}

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.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Batch integration updates can leave partial persisted state.

This loop writes integrations one-by-one and returns on first failure, so a single request can partially apply changes. For a PUT batch endpoint, this is a data-consistency risk.

💡 Suggested direction
 type RequestService interface {
+  UpsertIntegrations(ctx context.Context, viewer mediarequests.Viewer, integrations []mediarequests.Integration) ([]mediarequests.Integration, error)
 }

 func (h *RequestsHandler) HandleUpdateIntegrations(w http.ResponseWriter, r *http.Request) {
   // decode body...
-  updated := make([]mediarequests.Integration, 0, len(body.Integrations))
-  for _, integration := range body.Integrations {
-    result, err := h.service.UpsertIntegration(r.Context(), viewer, integration)
-    if err != nil {
-      writeRequestServiceError(w, err)
-      return
-    }
-    updated = append(updated, *result)
-  }
+  updated, err := h.service.UpsertIntegrations(r.Context(), viewer, body.Integrations)
+  if err != nil {
+    writeRequestServiceError(w, err)
+    return
+  }

   writeJSON(w, http.StatusOK, struct {
     Integrations []requestIntegrationResponse `json:"integrations"`
   }{Integrations: toIntegrationResponses(updated)})
 }
🤖 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/requests.go` around lines 395 - 403, The loop in the
PUT batch handler calls h.service.UpsertIntegration per item and returns on
first error, causing partial persistence; change this to an atomic operation by
delegating the whole slice to a transactional service call (e.g., implement and
call h.service.UpsertIntegrations(ctx, viewer, body.Integrations) or wrap the
loop in a service-managed transaction) so either all integrations are applied or
none are; on error, ensure you do not persist partial results and still return
the appropriate writeRequestServiceError response. Use the existing symbols
body.Integrations, h.service.UpsertIntegration as reference when adding the new
transactional method or wrapping logic so callers and tests can be updated
accordingly.

Comment on lines +27 to +35
ids := make([]string, 0, len(tmdbIDs))
for _, id := range tmdbIDs {
if id > 0 {
ids = append(ids, strconv.Itoa(id))
}
}
internalType := string(mediaType)
rows, err := p.items.LookupTMDBIDs(ctx, internalType, ids)
if 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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Skip repository lookup when filtered TMDB ID list is empty.

After filtering (id > 0), ids can be empty; calling LookupTMDBIDs with an empty list can trigger avoidable DB errors/work on some implementations.

Proposed fix
 	ids := make([]string, 0, len(tmdbIDs))
 	for _, id := range tmdbIDs {
 		if id > 0 {
 			ids = append(ids, strconv.Itoa(id))
 		}
 	}
+	if len(ids) == 0 {
+		return out, nil
+	}
 	internalType := string(mediaType)
 	rows, err := p.items.LookupTMDBIDs(ctx, internalType, ids)
📝 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
ids := make([]string, 0, len(tmdbIDs))
for _, id := range tmdbIDs {
if id > 0 {
ids = append(ids, strconv.Itoa(id))
}
}
internalType := string(mediaType)
rows, err := p.items.LookupTMDBIDs(ctx, internalType, ids)
if err != nil {
ids := make([]string, 0, len(tmdbIDs))
for _, id := range tmdbIDs {
if id > 0 {
ids = append(ids, strconv.Itoa(id))
}
}
if len(ids) == 0 {
return out, nil
}
internalType := string(mediaType)
rows, err := p.items.LookupTMDBIDs(ctx, internalType, ids)
if err != nil {
🤖 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/requests/presence.go` around lines 27 - 35, After filtering tmdbIDs
into ids, add a guard that if len(ids) == 0 you skip calling
p.items.LookupTMDBIDs and return immediately with the appropriate empty result
(e.g., empty slice/map and nil error) instead of invoking LookupTMDBIDs; update
the code around the ids variable and the LookupTMDBIDs call to short-circuit on
empty ids to avoid unnecessary DB work and errors.

Comment on lines +349 to +451
return nil, fmt.Errorf("begin request status transaction: %w", err)
}
defer tx.Rollback(ctx)

req, err := scanRequest(tx.QueryRow(ctx, `
UPDATE media_requests
SET status = $2,
updated_at = now(),
approved_at = CASE WHEN $2 = 'approved' AND approved_at IS NULL THEN now() ELSE approved_at END,
completed_at = CASE WHEN $2 = 'completed' AND completed_at IS NULL THEN now() ELSE completed_at END
WHERE id = $1
RETURNING `+requestColumns(), id, status))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("set request status: %w", err)
}
if err := r.recordEvent(ctx, tx, id, "status_"+string(status), actor, ""); err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, fmt.Errorf("commit request status transaction: %w", err)
}
return req, nil
}

func (r *Repository) MarkQueued(ctx context.Context, id string, update QueueUpdate, actor Viewer) (*Request, error) {
tx, err := r.pool.Begin(ctx)
if err != nil {
return nil, fmt.Errorf("begin request queue transaction: %w", err)
}
defer tx.Rollback(ctx)

externalStatus := strings.TrimSpace(update.ExternalStatus)
if externalStatus == "" {
externalStatus = "queued"
}
req, err := scanRequest(tx.QueryRow(ctx, `
UPDATE media_requests
SET status = 'queued',
outcome = 'active',
integration_kind = $2,
external_id = $3,
external_status = $4,
last_error = '',
updated_at = now(),
approved_at = CASE WHEN approved_at IS NULL THEN now() ELSE approved_at END
WHERE id = $1
RETURNING `+requestColumns(), id,
strings.TrimSpace(update.IntegrationKind),
strings.TrimSpace(update.ExternalID),
externalStatus,
))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("mark request queued: %w", err)
}
if err := r.recordEvent(ctx, tx, id, "status_queued", actor, externalStatus); err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, fmt.Errorf("commit request queue transaction: %w", err)
}
return req, nil
}

func (r *Repository) SetOutcome(ctx context.Context, id string, outcome Outcome, actor Viewer, message string) (*Request, error) {
tx, err := r.pool.Begin(ctx)
if err != nil {
return nil, fmt.Errorf("begin request outcome transaction: %w", err)
}
defer tx.Rollback(ctx)

req, err := scanRequest(tx.QueryRow(ctx, `
UPDATE media_requests
SET outcome = $2,
last_error = CASE
WHEN $2 = 'failed' THEN $3
WHEN $2 = 'active' THEN ''
ELSE last_error
END,
updated_at = now()
WHERE id = $1
RETURNING `+requestColumns(), id, outcome, strings.TrimSpace(message)))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("set request outcome: %w", err)
}
if err := r.recordEvent(ctx, tx, id, "outcome_"+string(outcome), actor, message); err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, fmt.Errorf("commit request outcome transaction: %w", err)
}
return req, 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.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Guard request state transitions against concurrent writers.

SetStatus, MarkQueued, and SetOutcome each update the same row without a lock or state precondition. Concurrent reconcile/admin actions can clobber each other and produce incorrect final state/event history.

Suggested direction
+ -- inside each transaction, lock the row first
+ SELECT id FROM media_requests WHERE id = $1 FOR UPDATE;
+
  UPDATE media_requests
  SET ...
- WHERE id = $1
+ WHERE id = $1
+   -- optionally enforce expected current state for legal transitions
+   -- e.g. outcome = 'active'
🤖 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/requests/repository.go` around lines 349 - 451, These methods
(SetStatus, MarkQueued, SetOutcome) update the same media_requests row without
any lock or precondition, allowing concurrent writers to clobber state; wrap the
update in a row lock and optionally validate the current state: begin the same
transaction as created (tx), run a SELECT id, status, outcome FROM
media_requests WHERE id = $1 FOR UPDATE using tx.QueryRow to lock the row and
read current values (use the same id param), validate or assert expected current
status/outcome if needed, then perform the UPDATE via tx (e.g., tx.QueryRow) and
continue calling r.recordEvent(ctx, tx, ...) and tx.Commit(ctx) as before;
update references: SetStatus, MarkQueued, SetOutcome, scanRequest, and
recordEvent so the lock/read and validation happen inside the transaction before
the UPDATE.

Comment on lines +657 to +659
if len(optionsRaw) > 0 {
_ = json.Unmarshal(optionsRaw, &integration.Options)
}

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Do not swallow integration options decode failures.

Ignoring json.Unmarshal errors masks bad persisted payloads and silently falls back to {}, which can lead to confusing integration behavior.

Proposed fix
  if len(optionsRaw) > 0 {
-		_ = json.Unmarshal(optionsRaw, &integration.Options)
+		if err := json.Unmarshal(optionsRaw, &integration.Options); err != nil {
+			return Integration{}, fmt.Errorf("unmarshal request integration options: %w", err)
+		}
  }
📝 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 len(optionsRaw) > 0 {
_ = json.Unmarshal(optionsRaw, &integration.Options)
}
if len(optionsRaw) > 0 {
if err := json.Unmarshal(optionsRaw, &integration.Options); err != nil {
return Integration{}, fmt.Errorf("unmarshal request integration options: %w", err)
}
}
🤖 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/requests/repository.go` around lines 657 - 659, The current code
swallows json.Unmarshal errors when decoding optionsRaw into
integration.Options; change the block in repository.go so that you capture the
error returned by json.Unmarshal(optionsRaw, &integration.Options) and handle it
instead of discarding it—either return the error from the enclosing function
(propagate) or log and wrap it with context (including identifiers for the
affected integration) so corrupted persisted payloads aren’t silently replaced
by {}. Ensure you reference optionsRaw and integration.Options and update the
function signature/return path as needed to propagate the unmarshalling error.

Comment on lines +242 to +252
func (s *Service) CreateRequest(ctx context.Context, viewer Viewer, input CreateRequestInput) (*Request, error) {
if err := validateViewer(viewer); err != nil {
return nil, err
}
normalized, err := normalizeCreateInput(input)
if err != nil {
return nil, err
}
s.enrichExternalIDs(ctx, &normalized)

available, err := s.lookupAvailable(ctx, normalized.MediaType, []int{normalized.TMDBID})

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add service configuration guard in CreateRequest to avoid nil dereference panics.

CreateRequest uses s.store/s.tmdb paths without the configuration check used by Search, Discover, and GetDetail. A misconfigured service can panic here instead of returning a controlled error.

Proposed fix
 func (s *Service) CreateRequest(ctx context.Context, viewer Viewer, input CreateRequestInput) (*Request, error) {
+	if s == nil || s.store == nil || s.tmdb == nil {
+		return nil, fmt.Errorf("request service is not configured")
+	}
 	if err := validateViewer(viewer); err != nil {
 		return nil, err
 	}
📝 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
func (s *Service) CreateRequest(ctx context.Context, viewer Viewer, input CreateRequestInput) (*Request, error) {
if err := validateViewer(viewer); err != nil {
return nil, err
}
normalized, err := normalizeCreateInput(input)
if err != nil {
return nil, err
}
s.enrichExternalIDs(ctx, &normalized)
available, err := s.lookupAvailable(ctx, normalized.MediaType, []int{normalized.TMDBID})
func (s *Service) CreateRequest(ctx context.Context, viewer Viewer, input CreateRequestInput) (*Request, error) {
if s == nil || s.store == nil || s.tmdb == nil {
return nil, fmt.Errorf("request service is not configured")
}
if err := validateViewer(viewer); err != nil {
return nil, err
}
normalized, err := normalizeCreateInput(input)
if err != nil {
return nil, err
}
s.enrichExternalIDs(ctx, &normalized)
available, err := s.lookupAvailable(ctx, normalized.MediaType, []int{normalized.TMDBID})
🤖 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/requests/service.go` around lines 242 - 252, CreateRequest currently
calls service backends (e.g., s.store, s.tmdb, lookupAvailable) without the
configuration guard used in Search/Discover/GetDetail, which can cause nil
dereference panics on a misconfigured Service; add the same configuration check
at the start of CreateRequest (validate that the service is configured and
required subsystems like s.store and s.tmdb are non-nil or call the existing
ensure-config helper used elsewhere), and if not configured return the standard
configuration error (e.g., ErrServiceNotConfigured) instead of proceeding to
call s.store/s.tmdb or lookupAvailable.

Comment on lines +155 to +157
if len(matches) > 0 {
return matches[0], 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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid falling back to an arbitrary lookup result when TVDB ID doesn't match.

Line 155 falls back to matches[0] even when no exact TVDBID match is found, which can submit the wrong series.

🔧 Proposed fix
 	for _, match := range matches {
 		if match.TVDBID == tvdbID {
 			return match, nil
 		}
 	}
-	if len(matches) > 0 {
-		return matches[0], nil
-	}
 	return seriesResource{}, fmt.Errorf("sonarr: no series found for tvdb_id %d", tvdbID)
📝 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 len(matches) > 0 {
return matches[0], nil
}
for _, match := range matches {
if match.TVDBID == tvdbID {
return match, nil
}
}
return seriesResource{}, fmt.Errorf("sonarr: no series found for tvdb_id %d", tvdbID)
🤖 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/requests/sonarr/client.go` around lines 155 - 157, The code
currently returns matches[0] whenever matches is non-empty even if none have the
requested TVDB ID, which can submit the wrong series; update the logic to scan
the matches slice for an item whose TVDBID (match.TVDBID) exactly equals the
requested TVDB ID and return that match, and only if no exact match is found
return a not-found error (do not fall back to matches[0]); modify the block
around the matches variable in client.go to perform this exact-match check and
return a clear error (e.g., ErrSeriesNotFound or a descriptive error) when no
exact TVDBID match exists.

Comment on lines +200 to +201
pendingTMDBID={createRequest.variables?.tmdb_id}
isSubmitting={createRequest.isPending}

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Match pending request by both tmdb_id and media_type.

Current pending-card detection keys only on tmdb_id, which can collide between movies and series and show a spinner/disable on the wrong card.

Suggested fix
- isSubmitting={createRequest.isPending && pendingTMDBID === item.tmdb_id}
+ isSubmitting={
+   createRequest.isPending &&
+   createRequest.variables?.tmdb_id === item.tmdb_id &&
+   createRequest.variables?.media_type === item.media_type
+ }

Also applies to: 466-467, 551-552

🤖 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 `@web/src/pages/Requests.tsx` around lines 200 - 201, The pending-card logic
currently only keys off createRequest.variables?.tmdb_id (passed as
pendingTMDBID) so movies and TV can collide; update the component props and
usage to also pass createRequest.variables?.media_type (e.g., pendingMediaType)
and change the pending detection to require both tmdb_id and media_type match
while still using createRequest.isPending for isSubmitting; apply the same
change to the other two occurrences where createRequest.variables?.tmdb_id and
createRequest.isPending are used so all pending-card checks compare both tmdb_id
and media_type.

@Quick104
Quick104 force-pushed the t3code/discover-studios-networks-genres branch from 27d94fe to fc237f4 Compare May 24, 2026 23:53
@Silo-Server Silo-Server deleted a comment from cursor Bot May 24, 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: 27d94fe01e

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +382 to +384
if active.Status == StatusApproved {
return s.submitApprovedRequest(ctx, *active, viewer)
}

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 Retry failed queued requests by resubmitting to integrations

When a request fails after it has already been queued/downloading in Radarr/Sonarr, Retry only flips outcome back to active and returns unless status is exactly approved. In that common case the status remains queued/downloading, so no new submission is attempted and the retry action is effectively a no-op for admins. This leaves failed requests stuck unless they are manually edited in storage.

Useful? React with 👍 / 👎.

Comment on lines +140 to +141
<TabsTrigger value="series">Series</TabsTrigger>
</TabsList>

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 Hide unsupported Series tab on genre browse pages

The genre browse UI always renders a Series tab, but some bundled genres are movie-only (SeriesID = 0) and the backend rejects media_type=series for them with ErrInvalidInput. Exposing that tab sends users into an avoidable error path for genres like horror/romance instead of preventing the unsupported selection.

Useful? React with 👍 / 👎.

Comment on lines +155 to +157
if len(matches) > 0 {
return matches[0], nil
}

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 Do not fall back to first Sonarr lookup match

If Sonarr returns multiple results and none matches the requested TVDB ID, lookupSeries currently returns matches[0] anyway, which can submit a completely different show than the one requested. This is a data-integrity bug that can enqueue the wrong series in Sonarr whenever TVDB lookup results are ambiguous or stale; the method should fail instead of guessing.

Useful? React with 👍 / 👎.

export default function RequestDetail() {
const navigate = useNavigate();
const params = useParams<{ mediaType: string; tmdbId: string }>();
const mediaType = (params.mediaType === "series" ? "series" : "movie") as "movie" | "series";

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 Reject unknown request detail media types

The detail page coerces any unknown :mediaType route segment to movie, so a TMDB-style deep link like /requests/tv/1399 fetches movie details for ID 1399 instead of the intended series. Because movie and TV IDs can overlap, users can be shown and request the wrong title rather than getting an explicit invalid-route error or alias mapping.

Useful? React with 👍 / 👎.

Comment on lines +382 to +384
if active.Status == StatusApproved {
return s.submitApprovedRequest(ctx, *active, viewer)
}

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 Retry failed queued requests by resubmitting to integrations

After Retry flips outcome back to active, it only re-submits when the request status is exactly approved. Failed submissions commonly retain queued/downloading status, so retrying them just updates outcome and returns without calling Radarr/Sonarr again, leaving the request stuck and making the retry action a no-op.

Useful? React with 👍 / 👎.

Comment on lines +140 to +141
<TabsTrigger value="series">Series</TabsTrigger>
</TabsList>

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 Hide unsupported Series tab on genre browse pages

The genre browse UI always renders a Series tab, but some bundled genres are movie-only (series_supported is false). Selecting Series for those genres causes backend validation to fail (genreID == 0), so users are offered a tab that cannot succeed and are pushed into an avoidable error state.

Useful? React with 👍 / 👎.

Comment on lines +155 to +157
if len(matches) > 0 {
return matches[0], nil
}

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 Do not fall back to first Sonarr lookup match

When TVDB matching fails, the code falls back to matches[0] from Sonarr lookup results. That can submit a different show than requested whenever multiple candidates are returned (common for remakes/ambiguous titles), which is a correctness issue because the request can be fulfilled against the wrong series.

Useful? React with 👍 / 👎.

export default function RequestDetail() {
const navigate = useNavigate();
const params = useParams<{ mediaType: string; tmdbId: string }>();
const mediaType = (params.mediaType === "series" ? "series" : "movie") as "movie" | "series";

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 Reject unknown request detail media types

The route param coercion treats any non-series value as movie, so invalid paths (for example /requests/tv/:id) silently fetch movie details instead of rejecting the URL. Because TMDB IDs overlap across types, this can render a valid but incorrect title and mislead users rather than surfacing a clear error.

Useful? React with 👍 / 👎.

@Quick104 Quick104 closed this May 25, 2026
@Quick104
Quick104 deleted the t3code/discover-studios-networks-genres branch May 25, 2026 00:02

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 30396df. Configure here.

Comment thread internal/api/router.go
)
requestSvc.SetSecretResolver(settingsRepo)
requestSvc.SetFulfillmentAdapters(radarr.NewClient(nil), sonarr.NewClient(nil))
requestHandler = handlers.NewRequestsHandler(requestSvc)

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.

Two independent TMDB clients bypass shared rate limiting

Low Severity

The router creates a brand-new tmdb.NewClient(tmdbAPIKey, 40) exclusively for the request service, separate from any existing TMDB client used elsewhere in the application. Since each client tracks its own rate-limit budget independently, the combined TMDB request volume from both clients can exceed TMDB's API rate limits, leading to 429 errors under moderate load. The client instance could be shared or coordinated instead of duplicated.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 30396df. Configure here.

fluxis added a commit to fluxis/silo-server that referenced this pull request Jun 17, 2026
…ups reveal, hot-row + stats index

From the full audiobook code review (EXPLAIN + slow-query trace on live):

- Silo-Server#1 (P0, detail-page killer): NeedsCriticalProbeRepair required video codec/
  resolution/tracks, which audio-only files never have, so PlaybackProbeEnsurer
  re-ran ffprobe per file on every detail/watch load (up to N serial spawns for
  an N-track book) and never converged. Gate video-field checks on the file
  actually having a video stream. TDD.
- Silo-Server#3 (P0): abs session-sync rewound the resume cursor — UpdateProgressPosition
  did an unconditional SET with no monotonic guard, ignored its error, and
  no-op'd when no row existed (first-listen resume lost). Now a finish-preserving
  GREATEST upsert; caller logs failures.
- Silo-Server#4 (P0 perf): progress reports fired every ~10s invalidated all of
  catalogKeys.all → refetched every active browse/detail query incl the 13k
  audiobook group lists. Scope invalidation to the reported item's detail.
- Silo-Server#6 (P1 perf): Authors/Narrators page rendered all ~13k groups + cover images
  at once (main-thread freeze). Incremental reveal: render a capped window, grow
  on scroll via IntersectionObserver.
- Silo-Server#10: throttle abs TouchToken last_seen upsert (one per token per 5min) — same
  hot-row contention class as the device fix.
- Silo-Server#8: index abs_playback_sessions (user_id, profile_id, started_at) for the
  listening-stats aggregations.

Deferred (need contract/validation): listening-time idempotency (client delta-vs-
cumulative), scanner deleted-file reconcile, abs session retention job, abs list-
handler batch fetch, scanner-output P2s (need re-backfill).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Quick104 added a commit that referenced this pull request Jun 17, 2026
* perf(catalog): fix audiobook detail N+1 + slow people facets

Audiobook detail pages were slow in proportion to track count (up to 433
files/book). Root causes, found by EXPLAIN ANALYZE on the live DB:

- effectiveAudioSelection ran 3-4 user-store queries (profile, audio pref,
  library pref) per file inside buildPlaybackInfo's loop, though the results
  are invariant across a request. Introduce a request-scoped audioPrefResolver
  that memoizes the store lookups (library prefs keyed by folder); a 400-file
  audiobook now issues each query once instead of per file. Selection logic is
  unchanged (audioPreference returns a copy so the original-language sentinel
  is still resolved per file).
- buildAudiobookExtension ran its four independent related-content queries
  serially; run them concurrently so latency is the slowest, not the sum.
- author/narrator browse facets did a full people-table scan; add a
  (kind, content_id, person_id) index so the facet resolves from an index-only
  scan of just that kind's credits (~112ms -> ~49ms on the live library).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf(catalog): cache audiobook author/narrator group browse

The Authors/Narrators audiobook pages were slow on cold load and slow again
after a hard refresh (fast only while the React Query client cache was warm).

Root cause (EXPLAIN ANALYZE on live, 31K-audiobook library): the grouped
browse query is ~234ms/page, there are ~13K distinct authors, and the client
pages through the entire list on every load (sequential 500-row requests). With
no server-side cache each of the ~20 pages re-ran the full aggregation
(COUNT(*) OVER() forces it), so a cold load was ~20x234ms. The client's 60s
staleTime was the only thing making a warm revisit fast; a refresh wiped it.

Fix: AudiobookGroupsCache caches the full sorted group list per (library,
group_by, sort, viewer) for 60s (matching the client staleTime, so no extra
staleness) and serves every page as an in-memory slice — one aggregation per
window instead of one per page, and a refresh is a cache hit. Also raise the
client page size 500->2000 so fewer sequential round-trips are needed now that
a larger page is a cheap slice.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf(settings): throttle per-request device last_seen upserts

Device-setting reads (HandleGetDeviceSetting, HandleGetEffectiveSettings,
HandleGetEffectiveSubtitleAppearance) each registered the request's device — an
INSERT ... ON CONFLICT upsert of last_seen_at on a single per-device row. A page
that fetches many settings fired hundreds of these concurrently; they serialized
on that row's lock (observed 100-237ms each, ~250 per page load in the slow
query log), taxing every settings fetch.

Throttle device registration to one upsert per (profile, device) per 5 minutes
via an in-process TTL cache, marking the device seen before the upsert so a
concurrent burst collapses to a single write. last_seen_at stays fresh to within
the window. Reads no longer issue a contended write on the hot path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf+fix(audiobooks): probe-repair, resume position, cache storm, groups reveal, hot-row + stats index

From the full audiobook code review (EXPLAIN + slow-query trace on live):

- #1 (P0, detail-page killer): NeedsCriticalProbeRepair required video codec/
  resolution/tracks, which audio-only files never have, so PlaybackProbeEnsurer
  re-ran ffprobe per file on every detail/watch load (up to N serial spawns for
  an N-track book) and never converged. Gate video-field checks on the file
  actually having a video stream. TDD.
- #3 (P0): abs session-sync rewound the resume cursor — UpdateProgressPosition
  did an unconditional SET with no monotonic guard, ignored its error, and
  no-op'd when no row existed (first-listen resume lost). Now a finish-preserving
  GREATEST upsert; caller logs failures.
- #4 (P0 perf): progress reports fired every ~10s invalidated all of
  catalogKeys.all → refetched every active browse/detail query incl the 13k
  audiobook group lists. Scope invalidation to the reported item's detail.
- #6 (P1 perf): Authors/Narrators page rendered all ~13k groups + cover images
  at once (main-thread freeze). Incremental reveal: render a capped window, grow
  on scroll via IntersectionObserver.
- #10: throttle abs TouchToken last_seen upsert (one per token per 5min) — same
  hot-row contention class as the device fix.
- #8: index abs_playback_sessions (user_id, profile_id, started_at) for the
  listening-stats aggregations.

Deferred (need contract/validation): listening-time idempotency (client delta-vs-
cumulative), scanner deleted-file reconcile, abs session retention job, abs list-
handler batch fetch, scanner-output P2s (need re-backfill).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf(audiobooks): batch-fetch abs list/shelf handlers (kill N+1)

handleSimilarItems, handleItemsInProgress, and handleGetMyProgress called
MediaStore.GetAudiobookByID once per row — up to ~500 single fetches (each a
few queries) on app open. Add GetAudiobooksByIDs (one access-scoped fetch +
people/series hydrated once for the whole set) and look results up from the
returned map, preserving order. Underlying primitives (GetByIDsWithAccess,
hydratePeople/Series) were already batch-capable.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(audiobooks): reconcile deleted files on scan + prune session history

#5: ScanAudiobookFolder only ever upserted — deleted/renamed books leaked
media_items/media_files/memberships forever. Mirror the ebook reconcile: collect
seenPaths during the walk, MarkMissing files no longer on disk, then
reconcileLibraryMemberships. Safety mirrors ebooks/video: an inaccessible root
(unmounted source) is skipped entirely, and a walk that saw zero files while the
DB has rows only reconciles after operator cleanup confirmation
(ebookEmptyCleanupAllowed) — so a flapping mount can't wipe the catalog. Soft
mark only; the existing grace-period purge hard-deletes later. Reconcile runs
only on a fully-completed (non-cancelled) scan. (#9 coarse case already handled:
audiobookFolderShouldSkip skips unchanged folders; per-file reuse deferred.)

#8-retention: abs_playback_sessions grew unbounded (one row per play-start, never
deleted) and fed every listening-stats scan. Add an hourly sweep in
SessionCleaner: close abandoned open sessions (no /close, stopped syncing >24h)
and delete closed sessions older than 90 days. Mirrors the recommendation_cache /
missing-files prune pattern.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(audiobooks): address max-effort code-review findings

From /code-review max on the pre-PR diff:
- DATA RACE (P0): SessionCleaner.lastABSSessionPrune is read+written by both the
  15s ticker goroutine and the shutdown-path CleanStale call (main.go defers
  Stop() to after that call). Guard the prune-due gate with a mutex. (CleanStale
  was stateless before this branch, so concurrent calls were previously safe.)
- ScanAudiobookFolder hardcoded fullScan=true into the empty-walk cleanup guard,
  but it's also called from ScanSubtree (incremental scans). An empty subtree
  scan would wrongly consume the operator's one-shot empty-cleanup allowance and
  warn. Thread a real fullScan flag (true from ScanFolder, false from the two
  subtree call sites), mirroring the ebook path.
- Revert UpdateProgressPosition to UPDATE-only (drop the INSERT-on-missing):
  keep the monotonic GREATEST + finish guard that fixes the resume rewind, but
  restore the no-op-on-missing contract so a stray sync tick can't resurrect
  just-cleared progress or create a zero-duration continue-listening row.
- Clamp the audiobook-groups handler limit (paging moved into the cache, leaving
  the old 500/page bound stranded); also gofmt the Scanner struct.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(audiobooks): address review feedback for scanner and stats

* fix(audiobooks): address review feedback

* fix(audiobooks): retry failed session prune

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: Quick <[email protected]>
CoffeeKnyte added a commit that referenced this pull request Jun 23, 2026
proxyToTranscodeNode appended the client's raw query string to the internal
transcode-node URL and logged that URL on transport failure. When a remote
transcode runs without a separate proxy node, that query carries
?st=<signed JWT> — a 24h bearer reconstruction descriptor exposing the
media path and recipe claims — placing the token into internal requests and
error logs.

Strip the "st" param before building targetURL, preserving any other query
params. The token is neither forwarded to the node nor present in the
logged URL. Header-forwarding of the token (so the node can reconstruct) is
a separate follow-up (#6).
Quick104 added a commit that referenced this pull request Jul 2, 2026
…pat) (#174)

* feat(playback): unified restart-resilient playback via shared TranscodeManager

Make direct, remux, and native HLS transcode sessions survive a server
restart through one shared flow instead of per-method paths. A missing
in-memory session becomes a reconstruct trigger, not a 404: the server
rebuilds the session from a tiny durable recipe card plus the position the
client re-supplies on its next request.

- internal/playback/transcode_manager.go: shared TranscodeManager owning the
  transcodes map, recipe-card lifecycle, reconstruct single-flight +
  concurrency cap, LoadOrReconstructSession front door, ReconstructSession /
  ReconstructTranscode, and orphan cleanup. ~90% is logic moved out of the
  native handler (no behavior change), not new surface.
- internal/playback/recipecard.go + recipecard_postgres.go: RecipeCard with a
  PlayMethod discriminator (direct/remux/transcode; empty decodes as transcode
  for back-compat) behind a swappable, nil-safe RecipeStore interface backed by
  transcode_recipes.
- internal/playback/session.go: RegisterReconstructed inserts a rebuilt Session
  under its existing id (no UUID mint, no limit double-count, race-yielding).
- internal/playback/transcode.go: CloseProcess keeps the output dir so a
  reconstruct winner keeps serving; Close removes it.
- internal/api/handlers: drain the transcode lifecycle into the manager; wire
  reconstruct into the stream/segment serve paths; re-bind ownership to the live
  caller (refuse userID==0/mismatch); card-aware orphan cleanup.
- migrations: add transcode_recipes (expires_at TTL, filter-on-read, indexed).

Ownership stays two-factor: an authenticated caller AND a session.UserID that
matches; the card stores no secrets and identity is re-resolved per request.

Tests: recipe-card round-trip/legacy-decode/disabled-noop, RegisterReconstructed
insert/race/concurrency, close-vs-close-process dir semantics, the
LoadOrReconstructSession status matrix, and the reconstruct concurrency cap.

AI-use: implemented with AI assistance (design, implementation, adversarial review).

* feat(jellycompat): reconstruct transcodes across restart via shared manager

Bring Jellyfin (jellycompat) HLS playback onto the same restart-resilient flow
as the native path. Previously jellycompat owned a separate PlaybackHandler with
a private transcodes map and a duplicated transcode lifecycle that never grew the
reconstruct half, so an in-flight Jellyfin transcode died on restart and the next
segment request 404'd.

- Embed the shared playback.TranscodeManager and delete the duplicate lifecycle,
  so jellycompat gets reconstruct, the concurrency cap, the node-affinity rule,
  and the card lifecycle for free.
- internal/jellycompat/playback_sessions_postgres.go: DurableCompatPlaybackStore,
  a write-through cache over jellycompat_playback_sessions behind the new
  CompatPlaybackStore interface (nil pool degrades to cache-only). This persists
  the load-bearing PlaySessionId -> UpstreamSessionID mapping (plus media sources,
  route item id, seek) so it survives a restart instead of vanishing with the map.
- Write a recipe card on compat transcode start keyed by the upstream session id,
  using the native StreamAppUserID so the ownership re-bind matches; reconstruct
  the upstream session and the transcode seeked to the requested seg_NNNNN.
- migrations: add jellycompat_playback_sessions (expires_at TTL + compat_token
  index, full PlaybackSession in data JSONB).

Auth is mapped to the native user id before reconstruct so the same two-factor
ownership check and userID==0/mismatch refusal apply unchanged.

Tests: DB-gated (SILO_TEST_DATABASE_URL) durable-store round-trip proving a
session written by one instance reloads in a fresh one (the restart case), plus
a nil-pool cache-only path; existing handler tests updated to the manager.

AI-use: implemented with AI assistance (design, implementation, adversarial review).

* docs(playback): consolidate unified playback reconstruction design

Replace the three overlapping playback docs (the native Postgres
restart-resilience spec, the jellycompat plan, and the unification spec) with a
single self-contained design at
docs/superpowers/specs/unified-playback-reconstruct.md.

The doc leads with the unified design — the one-idea reconstruct model, a strong
visual flow of a restart mid-playback, the shared TranscodeManager + recipe card,
the two swappable durable stores, security, the concurrency cap and node-affinity
constraint, preconditions, and verification. The design history and rationale
(reconstruct-not-rehydrate, phased delivery, Redis-vs-Postgres, token-as-
descriptor, failure analysis) move to an appendix. It references no other md file.

AI-use: written with AI assistance.

* fix(playback): address review on restart-resilient playback

Four fixes from PR review of the unified reconstruction work:

- Rewrite the recipe card on audio-track change. HandleChangeAudioTrack only
  updated the in-memory session/transcode, so after a restart reconstruct
  resumed with the stale AudioTrackIndex/TranscodeAudio (and stale play method)
  from the start-time card. Re-save the card (direct/remux/transcode) with the
  switched state, mirroring the start-card pattern.
- Guard nil TranscodeManager in LoadOrReconstructSession and ReconstructSession.
  StreamHandler.TM is documented optional (tests/minimal setups); a missing
  session previously panicked in recipeEnabled instead of returning
  SessionMissing. ReconstructTranscode already guarded nil; make the two
  siblings consistent.
- Reject direct/remux cards in doReconstructTranscode before spawning ffmpeg, so
  a non-transcode card id can never enter the HLS reconstruction path.
- Log a non-success status from the remote transcode-node DELETE in
  CloseTranscodeSession; a 401/404/500 was previously silent.

AI-use: implemented with AI assistance.

* fix(playback): harden restart-resilient compat sessions

* feat(playback): token-carried reconstruction across restarts

Build on the shared TranscodeManager (introduced earlier in this branch) so a
playback session survives an API-server or transcode-node restart without the
client re-negotiating, and retire the Postgres transcode_recipes store in favor
of a recipe carried inside the signed stream token.

- RecipeCard encodes the byte-affecting encode parameters and rides inside the
  stream token; LoadOrReconstructSession rebuilds the in-memory Session (and,
  for integrated transcodes, the ffmpeg process) on a cold miss, single-flighted
  per session and paced by a spawn semaphore. Removes recipecard_postgres.go and
  the 20260617233705_add_transcode_recipes migration.
- transcodenode reconstructs a lost ffmpeg node-side from the forwarded token.
- TR-lease: proxy/streamauth enforce a revocation deny-marker on every served
  segment, with a 500ms Redis timeout, a bounded per-session "allowed" cache
  (3s TTL, expiry-first graceful eviction), and a degraded-fail-open counter.

Review hardening folded in:
- Manifest/segment handlers do the in-memory session lookup first and only
  verify the stream token on a reconstruct miss (token HMAC was per-segment).
- Copy-mode reconstruct never applies the encoded-only seg*dur seek, at spawn
  time or via the recovery path: RestartSeekTarget reports "unresolved" for a
  copy session whose manifest cannot yet map the segment, so the client retries
  instead of seeking to a fabricated source time.
- Crash teardown is a compare-and-delete (CloseTranscodeSessionIf returns
  whether it matched); the crash closure tears down the playback session only
  when it matched, so a session reconstructed under the same id is not killed.
- Reconstruct enforces the same per-user stream/transcode caps as a fresh start
  (RegisterReconstructedWithLimits), closing a token-replay slot bypass.

AI-use disclosure: implemented with AI assistance (Claude Code), including a
two-round multi-agent adversarial review whose findings drove the hardening.

* feat(jellycompat): node-side transcode reconstruct via shared recipe store

Make Jellyfin-compat playback sessions survive a server or transcode-node
restart by reusing the shared TranscodeManager reconstruct path and a durable
recipe store, on top of the durable compat session store added earlier in this
branch.

- Node-side transcode reconstruct goes through the shared recipe store; the
  recipe is persisted to the control-plane store (Redis) when a dedicated
  transcode node is used so the node can rebuild ffmpeg after its own restart.
- Adopt the shared manager's API (3-arg OnFFmpegCrash carrying the dead session,
  guarded CloseTranscodeSessionIf, RegisterReconstructedWithLimits).

Review hardening folded in:
- Recipe lifecycle: noderecipe.Store gains Delete, called on deliberate
  teardown (stop, method-switch discard, node stop/force-reload) so a stopped
  session cannot be resurrected by a buffered request after a node restart;
  crash paths intentionally keep the recipe so a resume can reconstruct.
- Crash closure tears down the upstream session only when the guarded transcode
  close matched, so a reconstructed successor is never left orphaned.
- Copy-mode segment recovery surfaces a retryable not-found instead of a
  wrong-position restart, matching the native and node paths.
- Durable Update is now a SELECT ... FOR UPDATE transaction, removing the
  lost-update clobber that could silently drop a transcode recipe.
- Empty-token route resolution no longer falls back to an unbounded full-table
  scan; DB expiry filters bind the injected clock; the redundant re-Get is gone.

AI-use disclosure: implemented with AI assistance (Claude Code), including a
two-round multi-agent adversarial review whose findings drove the hardening.

* docs(playback): consolidate restart-resilient playback design

Replace the superpowers spec with a single architecture record describing the
token-carried recipe card, the shared TranscodeManager reconstruct path for
direct/remux/transcode, the jellycompat durable session + node recipe store, and
the revocation-lease model with its fail-open tradeoff.

AI-use disclosure: written with AI assistance (Claude Code).

* docs(playback): correct jellycompat node-recipe rationale in comments

The noderecipe / transcode-node / jellycompat comments justified the Redis
recipe store with "a Jellyfin client cannot round-trip a token". The real
reason: the node-hop token is server-minted and could carry the recipe, but the
recipe is mutated in place under a stable session id (a /Sessions/Playing/Progress
audio switch restarts ffmpeg without re-minting the client's token) and a
third-party Jellyfin client cannot be driven to refresh a stale token, so the
node must reconstruct from a server-authoritative, node-reachable store.

Aligns the comments with docs/architecture/restart-resilient-playback.md §10.
Comment-only; no behavior change.

* refactor(playback): remove deny-lease revocation, defer to future PR

The deny-lease stream-revocation mechanism (the internal/streamauth
package, its silo:streamauth:<sid> Redis markers, the proxy Allowed()
enforcement, and the admin Stop/Terminate deny write) only ever enforced
on the offload-proxy topology and was a silent no-op on the integrated
single box and the dedicated transcode node. Rather than ship a partial
revocation feature that looks complete but isn't, remove it wholesale and
defer a uniform cross-topology revocation design to a dedicated follow-up.

Removed: internal/streamauth (package + tests); the LeaseDenier field,
StreamLeaseDenier interface, and denyStreamLease helper in playback.go;
the admin deny write; the router/main wiring; and the proxy verifyToken
Allowed() gate. The unified-reconstruct core (recipe-token,
LoadOrReconstructSession) is orthogonal and untouched.

Known limitation (now on every topology): admin Terminate and user Stop
tear down the live in-memory session and ffmpeg producer, but a still-valid
stream token can reconstruct the session until its 24h TTL expires. No
node-side byte-withholding ships in this PR.

docs/architecture/restart-resilient-playback.md is updated to mark the
revocation/deny-lease sections as deferred and to drop the overstated
"instant revocation on admin kill" claim.

* fix(playback): allow zero-caller bearer on transcode reconstruct

The authless HLS transcode delivery routes (master.m3u8 / segment) treat
the session UUID as the bearer credential, so a real request carries
requestUserID == 0. The live serve path already allows this, but
ReconstructSession hard-rejected a zero caller, so a request that worked
before a restart became SessionMissing -> 404 after the in-memory session
was gone, breaking the restart resilience these routes advertise.

Match the live-path contract in LoadOrReconstructSession: allow a zero
caller (UUID-as-bearer) and refuse only a non-zero caller that mismatches
the card owner. The reconstructed session is bound to card.UserID either
way. Adds TestReconstructSession_Ownership covering both cases.

* fix(jellycompat): re-persist recipe on local audio switch

A Jellyfin client switching audio on an integrated/local compat transcode
restarted live ffmpeg with the new track but did not re-persist
PlaybackSession.Recipe. The remote branch already re-persists via
startRemoteTranscode -> persistTranscodeRecipe. After a central restart,
reconstruct rebuilt ffmpeg from the stale Recipe.AudioTrackIndex, so the
integrated session resumed on the original audio track.

Persist the updated recipe (best-effort) after a successful Restart in the
local branch, mirroring the remote branch, so the durable
Recipe.AudioTrackIndex tracks live ffmpeg. Adds a regression test.

* fix(playback): strip stream token from proxied transcode-node URL

proxyToTranscodeNode appended the client's raw query string to the internal
transcode-node URL and logged that URL on transport failure. When a remote
transcode runs without a separate proxy node, that query carries
?st=<signed JWT> — a 24h bearer reconstruction descriptor exposing the
media path and recipe claims — placing the token into internal requests and
error logs.

Strip the "st" param before building targetURL, preserving any other query
params. The token is neither forwarded to the node nor present in the
logged URL. Header-forwarding of the token (so the node can reconstruct) is
a separate follow-up (#6).

* fix(playback): fail open on transient limit-provider error in reconstruct

During the reconstruct wave right after a restart (Postgres under peak
load), a transient limit-provider DB error was collapsed into a hard 404,
permanently stopping playback for a user within their limits. limitsForUser
wrapped any provider error, RegisterReconstructedWithLimits propagated it,
and ReconstructSession mapped every error to SessionMissing -> 404 -
indistinguishable from a genuine over-cap rejection.

Distinguish the two: tag provider errors with a new ErrLimitProviderUnavailable
sentinel and, during reconstruct, fail OPEN on a provider error (admit via
RegisterReconstructed + log a degraded warning) rather than refuse - mirroring
the reliability-first fail-open-on-dependency-error philosophy. A genuine
ErrTooManyStreams / ErrTooManyTranscodes over-cap still refuses. Adds tests
for both the fail-open and still-refused paths.

* fix(playback): forward stream token to transcode node as header

The dedicated transcode node's reconstruct path reads the stream token only
from the X-Silo-Stream-Token header, but proxyToTranscodeNode forwarded only
the node-API bearer token (and #5 now strips st from the URL). So when the
central API proxied to the node and the node self-restarted, it could not
reconstruct from the recipe-complete native token -> 404.

Capture st before stripping it from the URL, verify it at the API boundary
(streamtoken.Verify + SessionID match, mirroring the node's own check), and
forward it as X-Silo-Stream-Token. Best-effort: a missing/invalid token never
blocks the live proxy, and the token is still kept out of the forwarded URL
and logs.

* fix(playback): restart node ffmpeg on native remote audio switch

A native audio-track switch on an offloaded/remote transcode was a no-op at
the node yet returned 200 with a fresh URL: HandleChangeAudioTrack restarted
ffmpeg only when the API owned a LOCAL TranscodeSession, so for an offloaded
transcode the node kept serving the OLD audio (the node consults the token
only on a session miss). The replacement URL was also minted from identity-
only claims, so a later node restart 404'd.

For the offloaded transcode case (detected via session.TranscodeNodeURL),
POST a fresh /transcode/start to the node with the new AudioTrackIndex
(handleStart tears down and restarts ffmpeg) and mint the replacement proxy
URL from a full RecipeCard so reconstruct survives a node restart. The encode
recipe is derived from the durable session target fields plus the file,
mirroring HandleStartTranscode. A concrete SegmentDuration
(playback.DefaultSegmentDuration) is embedded rather than 0: the node's token
completeness gate treats SegmentDuration<=0 as incomplete and falls back to a
recipe store the native path never populates, which would 404 on a node
restart - the exact resilience this path provides. A failed node POST now
surfaces 502 rather than a false 200. Remux and non-offloaded (local)
transcode paths keep their prior identity-claim URLs unchanged.

Known limitation: Session does not persist the original SegmentDuration or
SubtitleTrackIndex/SubtitleBurnIn, so a remote audio switch resets subtitle
selection to none and assumes the default segment length; a client that
started with a non-default segment length will resegment on switch. Making
that state durable on the session is a follow-up.

* docs(playback): scrub stale deny-lease/revalidator comments

The deny-lease revocation mechanism and its "central revalidator" were removed
earlier in this branch, but four comments still described them as live
(transcode_manager.go, noderecipe/store.go, streamtoken/token.go,
proxy/server.go). Reword them to match the shipped behavior: ownership claims
are re-resolved at reconstruct, the noderecipe store shares Redis only with the
node-session tracker, and a sub-TTL hard cut depends on a node-side revocation
mechanism that is deferred to a future PR.

* fix(jellycompat): surface durable playback-session write failures

DurableCompatPlaybackStore.Update applied the in-memory mutation and then
swallowed every Postgres commit-failure path, returning nil. Callers that
promise restart resilience (persistTranscodeRecipe's recipe write, the
upstream-session binds in streams.go) were told the session was durably
persisted when only the cache held it, so a transient DB hiccup could leave
the next restart reloading a stale row (wrong audio track) or 404ing.

updateDB now returns the genuine DB round-trip error (begin/query/unmarshal/
marshal/exec/commit); Update propagates it while still applying the in-memory
mutation so live state stays correct. A nil pool and a genuinely absent/expired
row remain best-effort (return nil) — only real infrastructure failures
propagate, so existing rollback paths fire exactly when durability is lost.

Part of #174

* fix(playback): re-inject stream token into proxied transcode manifests

API-proxied remote transcode manifests dropped the reconstruct token from
their segment URLs, so playback died after a node or API restart. When a
remote transcode has no separate proxy node, the client loads its manifest via
the API-local path; proxyToTranscodeNode strips the signed token ("st") from
the forwarded URL (keeping it off node URLs and logs, forwarded only as the
X-Silo-Stream-Token header), and the node builds relative segment URIs from
that token-less query. The segment URLs the client received carried no token,
and the proxy only re-attached the header when an incoming segment request
already had "st" — which it never did — so a restart made those segments
non-reconstructable and they 404'd.

proxyToTranscodeNode now rewrites the manifest body at the boundary: every
segment and #EXT-X-MAP init URI gets the client-facing, API-verified token
re-appended (new playback.AppendManifestQueryParam helper), so the client's
later segment fetches carry "st" again and reconstruct after a restart. The
token still never reaches the node URL or its logs. Only 200 .m3u8 responses
are rewritten (Content-Length corrected); segments stream through untouched.

Part of #174

* fix(playback): preserve subtitle/cadence recipe across offloaded audio switch

Switching audio on a remote (offloaded) transcode with burned-in subtitles
silently dropped them, and reset a non-default segment cadence. The offloaded
audio-switch restart rebuilt the node start request from Session state, but
Session/SessionStreamState retained no subtitle or segment-duration state
(only the live local ts.Opts() and the RecipeCard did), so the branch
hard-coded SubtitleTrackIndex:-1, SubtitleBurnIn:false and
SegmentDuration:Default — signing that altered recipe into the replacement
stream token. An audio switch then changed bytes beyond audio selection, and
any later reconstruct kept the wrong no-subtitle/wrong-cadence recipe.

Persist the byte-affecting recipe on the session: SubtitleTrackIndex,
SubtitleBurnIn and SegmentDuration are added to Session/SessionStreamState,
populated at start (finalizeTranscodeStart) and on post-restart reconstruct
(ReconstructSession from the card), carried forward on every audio-switch
state update, and read back when rebuilding the offloaded node request and its
recipe card. The restart now reproduces the exact live stream. Also resolves
the M-4b non-default segment_duration reset.

Part of #174

* fix(playback): serialize transcode spawn paths with a per-session lock

Reconstruct was single-flighted only against other reconstructs, so a
restart-driven segment reconstruct racing a quality/seek/audio fresh start
could spawn two ffmpeg processes writing the same output directory at once —
segment corruption, partial-write closes, orphaned processes, and skewed
active-job accounting. The atomic register-after-spawn (GetOrRegister / the
reconstruct compare-on-register) prevented a map leak but not the concurrent
disk writers, because the losing path had already spawned. The dedicated
transcode node had the same split between handleStart and spawnReconstruct.

Add a refcounted per-session lifecycle lock to both TranscodeManager and the
node Server, held across "check existing -> spawn -> register":
- reconstruct (doReconstructTranscode / spawnReconstruct) re-checks under the
  lock and yields to any live session instead of spawning a duplicate;
- the native and jellycompat fresh-start paths take the lock around their
  spawn+register (the native path also closes any session a reconstruct rebuilt
  in the meantime so its fresh ffmpeg is the sole writer);
- the node handleStart holds it across teardown+spawn+register.
The refcount drops the map entry once no path holds/waits, keeping it bounded.
GetOrRegisterTranscodeSession is removed — the lock supersedes it and keeping a
register-after-spawn primitive would invite reintroducing the race.

Part of #174

* fix(playback): serialize restart re-spawn under the session lifecycle lock

TranscodeSession.Restart() releases s.mu across cancel -> wait-for-done ->
re-exec and spawns ffmpeg into opts.OutputDir without holding the per-session
lifecycle lock. LockSessionLifecycle's contract (fresh start, restart,
reconstruct) requires restart to hold it too, but all five callers invoked
Restart unlocked: native audio-switch and segment-recovery, compat
audio-switch and segment-recovery, and the transcode-node segment-recovery.

A restart racing another restart (audio-switch vs segment-recovery) or a
fresh-start/reconstruct could land two ffmpeg processes writing the same
segment directory -- mixed timelines, init.mp4/segment mismatch, and an
orphaned-but-still-writing ffmpeg -- the exact concurrent-writer corruption
the lifecycle lock exists to prevent.

Add RestartSessionLocked (TranscodeManager) and restartSessionLocked (node
Server) that hold LockSessionLifecycle only across the cancel->respawn
transition, re-check that the handle is still the live mapped session under
the lock, and return ErrSessionSuperseded rather than re-spawning a stale
handle. Route all five call sites through them. The lock is released before
callers wait on segments so recovery latency is unchanged.

Tests: gating (restart blocks until the lifecycle lock frees, then spawns),
concurrent-restart serialization, and superseded re-check on both the manager
(covers native + compat) and node lock owners.

---------

Co-authored-by: Quick <[email protected]>
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…pat) (Silo-Server#174)

* feat(playback): unified restart-resilient playback via shared TranscodeManager

Make direct, remux, and native HLS transcode sessions survive a server
restart through one shared flow instead of per-method paths. A missing
in-memory session becomes a reconstruct trigger, not a 404: the server
rebuilds the session from a tiny durable recipe card plus the position the
client re-supplies on its next request.

- internal/playback/transcode_manager.go: shared TranscodeManager owning the
  transcodes map, recipe-card lifecycle, reconstruct single-flight +
  concurrency cap, LoadOrReconstructSession front door, ReconstructSession /
  ReconstructTranscode, and orphan cleanup. ~90% is logic moved out of the
  native handler (no behavior change), not new surface.
- internal/playback/recipecard.go + recipecard_postgres.go: RecipeCard with a
  PlayMethod discriminator (direct/remux/transcode; empty decodes as transcode
  for back-compat) behind a swappable, nil-safe RecipeStore interface backed by
  transcode_recipes.
- internal/playback/session.go: RegisterReconstructed inserts a rebuilt Session
  under its existing id (no UUID mint, no limit double-count, race-yielding).
- internal/playback/transcode.go: CloseProcess keeps the output dir so a
  reconstruct winner keeps serving; Close removes it.
- internal/api/handlers: drain the transcode lifecycle into the manager; wire
  reconstruct into the stream/segment serve paths; re-bind ownership to the live
  caller (refuse userID==0/mismatch); card-aware orphan cleanup.
- migrations: add transcode_recipes (expires_at TTL, filter-on-read, indexed).

Ownership stays two-factor: an authenticated caller AND a session.UserID that
matches; the card stores no secrets and identity is re-resolved per request.

Tests: recipe-card round-trip/legacy-decode/disabled-noop, RegisterReconstructed
insert/race/concurrency, close-vs-close-process dir semantics, the
LoadOrReconstructSession status matrix, and the reconstruct concurrency cap.

AI-use: implemented with AI assistance (design, implementation, adversarial review).

* feat(jellycompat): reconstruct transcodes across restart via shared manager

Bring Jellyfin (jellycompat) HLS playback onto the same restart-resilient flow
as the native path. Previously jellycompat owned a separate PlaybackHandler with
a private transcodes map and a duplicated transcode lifecycle that never grew the
reconstruct half, so an in-flight Jellyfin transcode died on restart and the next
segment request 404'd.

- Embed the shared playback.TranscodeManager and delete the duplicate lifecycle,
  so jellycompat gets reconstruct, the concurrency cap, the node-affinity rule,
  and the card lifecycle for free.
- internal/jellycompat/playback_sessions_postgres.go: DurableCompatPlaybackStore,
  a write-through cache over jellycompat_playback_sessions behind the new
  CompatPlaybackStore interface (nil pool degrades to cache-only). This persists
  the load-bearing PlaySessionId -> UpstreamSessionID mapping (plus media sources,
  route item id, seek) so it survives a restart instead of vanishing with the map.
- Write a recipe card on compat transcode start keyed by the upstream session id,
  using the native StreamAppUserID so the ownership re-bind matches; reconstruct
  the upstream session and the transcode seeked to the requested seg_NNNNN.
- migrations: add jellycompat_playback_sessions (expires_at TTL + compat_token
  index, full PlaybackSession in data JSONB).

Auth is mapped to the native user id before reconstruct so the same two-factor
ownership check and userID==0/mismatch refusal apply unchanged.

Tests: DB-gated (SILO_TEST_DATABASE_URL) durable-store round-trip proving a
session written by one instance reloads in a fresh one (the restart case), plus
a nil-pool cache-only path; existing handler tests updated to the manager.

AI-use: implemented with AI assistance (design, implementation, adversarial review).

* docs(playback): consolidate unified playback reconstruction design

Replace the three overlapping playback docs (the native Postgres
restart-resilience spec, the jellycompat plan, and the unification spec) with a
single self-contained design at
docs/superpowers/specs/unified-playback-reconstruct.md.

The doc leads with the unified design — the one-idea reconstruct model, a strong
visual flow of a restart mid-playback, the shared TranscodeManager + recipe card,
the two swappable durable stores, security, the concurrency cap and node-affinity
constraint, preconditions, and verification. The design history and rationale
(reconstruct-not-rehydrate, phased delivery, Redis-vs-Postgres, token-as-
descriptor, failure analysis) move to an appendix. It references no other md file.

AI-use: written with AI assistance.

* fix(playback): address review on restart-resilient playback

Four fixes from PR review of the unified reconstruction work:

- Rewrite the recipe card on audio-track change. HandleChangeAudioTrack only
  updated the in-memory session/transcode, so after a restart reconstruct
  resumed with the stale AudioTrackIndex/TranscodeAudio (and stale play method)
  from the start-time card. Re-save the card (direct/remux/transcode) with the
  switched state, mirroring the start-card pattern.
- Guard nil TranscodeManager in LoadOrReconstructSession and ReconstructSession.
  StreamHandler.TM is documented optional (tests/minimal setups); a missing
  session previously panicked in recipeEnabled instead of returning
  SessionMissing. ReconstructTranscode already guarded nil; make the two
  siblings consistent.
- Reject direct/remux cards in doReconstructTranscode before spawning ffmpeg, so
  a non-transcode card id can never enter the HLS reconstruction path.
- Log a non-success status from the remote transcode-node DELETE in
  CloseTranscodeSession; a 401/404/500 was previously silent.

AI-use: implemented with AI assistance.

* fix(playback): harden restart-resilient compat sessions

* feat(playback): token-carried reconstruction across restarts

Build on the shared TranscodeManager (introduced earlier in this branch) so a
playback session survives an API-server or transcode-node restart without the
client re-negotiating, and retire the Postgres transcode_recipes store in favor
of a recipe carried inside the signed stream token.

- RecipeCard encodes the byte-affecting encode parameters and rides inside the
  stream token; LoadOrReconstructSession rebuilds the in-memory Session (and,
  for integrated transcodes, the ffmpeg process) on a cold miss, single-flighted
  per session and paced by a spawn semaphore. Removes recipecard_postgres.go and
  the 20260617233705_add_transcode_recipes migration.
- transcodenode reconstructs a lost ffmpeg node-side from the forwarded token.
- TR-lease: proxy/streamauth enforce a revocation deny-marker on every served
  segment, with a 500ms Redis timeout, a bounded per-session "allowed" cache
  (3s TTL, expiry-first graceful eviction), and a degraded-fail-open counter.

Review hardening folded in:
- Manifest/segment handlers do the in-memory session lookup first and only
  verify the stream token on a reconstruct miss (token HMAC was per-segment).
- Copy-mode reconstruct never applies the encoded-only seg*dur seek, at spawn
  time or via the recovery path: RestartSeekTarget reports "unresolved" for a
  copy session whose manifest cannot yet map the segment, so the client retries
  instead of seeking to a fabricated source time.
- Crash teardown is a compare-and-delete (CloseTranscodeSessionIf returns
  whether it matched); the crash closure tears down the playback session only
  when it matched, so a session reconstructed under the same id is not killed.
- Reconstruct enforces the same per-user stream/transcode caps as a fresh start
  (RegisterReconstructedWithLimits), closing a token-replay slot bypass.

AI-use disclosure: implemented with AI assistance (Claude Code), including a
two-round multi-agent adversarial review whose findings drove the hardening.

* feat(jellycompat): node-side transcode reconstruct via shared recipe store

Make Jellyfin-compat playback sessions survive a server or transcode-node
restart by reusing the shared TranscodeManager reconstruct path and a durable
recipe store, on top of the durable compat session store added earlier in this
branch.

- Node-side transcode reconstruct goes through the shared recipe store; the
  recipe is persisted to the control-plane store (Redis) when a dedicated
  transcode node is used so the node can rebuild ffmpeg after its own restart.
- Adopt the shared manager's API (3-arg OnFFmpegCrash carrying the dead session,
  guarded CloseTranscodeSessionIf, RegisterReconstructedWithLimits).

Review hardening folded in:
- Recipe lifecycle: noderecipe.Store gains Delete, called on deliberate
  teardown (stop, method-switch discard, node stop/force-reload) so a stopped
  session cannot be resurrected by a buffered request after a node restart;
  crash paths intentionally keep the recipe so a resume can reconstruct.
- Crash closure tears down the upstream session only when the guarded transcode
  close matched, so a reconstructed successor is never left orphaned.
- Copy-mode segment recovery surfaces a retryable not-found instead of a
  wrong-position restart, matching the native and node paths.
- Durable Update is now a SELECT ... FOR UPDATE transaction, removing the
  lost-update clobber that could silently drop a transcode recipe.
- Empty-token route resolution no longer falls back to an unbounded full-table
  scan; DB expiry filters bind the injected clock; the redundant re-Get is gone.

AI-use disclosure: implemented with AI assistance (Claude Code), including a
two-round multi-agent adversarial review whose findings drove the hardening.

* docs(playback): consolidate restart-resilient playback design

Replace the superpowers spec with a single architecture record describing the
token-carried recipe card, the shared TranscodeManager reconstruct path for
direct/remux/transcode, the jellycompat durable session + node recipe store, and
the revocation-lease model with its fail-open tradeoff.

AI-use disclosure: written with AI assistance (Claude Code).

* docs(playback): correct jellycompat node-recipe rationale in comments

The noderecipe / transcode-node / jellycompat comments justified the Redis
recipe store with "a Jellyfin client cannot round-trip a token". The real
reason: the node-hop token is server-minted and could carry the recipe, but the
recipe is mutated in place under a stable session id (a /Sessions/Playing/Progress
audio switch restarts ffmpeg without re-minting the client's token) and a
third-party Jellyfin client cannot be driven to refresh a stale token, so the
node must reconstruct from a server-authoritative, node-reachable store.

Aligns the comments with docs/architecture/restart-resilient-playback.md §10.
Comment-only; no behavior change.

* refactor(playback): remove deny-lease revocation, defer to future PR

The deny-lease stream-revocation mechanism (the internal/streamauth
package, its silo:streamauth:<sid> Redis markers, the proxy Allowed()
enforcement, and the admin Stop/Terminate deny write) only ever enforced
on the offload-proxy topology and was a silent no-op on the integrated
single box and the dedicated transcode node. Rather than ship a partial
revocation feature that looks complete but isn't, remove it wholesale and
defer a uniform cross-topology revocation design to a dedicated follow-up.

Removed: internal/streamauth (package + tests); the LeaseDenier field,
StreamLeaseDenier interface, and denyStreamLease helper in playback.go;
the admin deny write; the router/main wiring; and the proxy verifyToken
Allowed() gate. The unified-reconstruct core (recipe-token,
LoadOrReconstructSession) is orthogonal and untouched.

Known limitation (now on every topology): admin Terminate and user Stop
tear down the live in-memory session and ffmpeg producer, but a still-valid
stream token can reconstruct the session until its 24h TTL expires. No
node-side byte-withholding ships in this PR.

docs/architecture/restart-resilient-playback.md is updated to mark the
revocation/deny-lease sections as deferred and to drop the overstated
"instant revocation on admin kill" claim.

* fix(playback): allow zero-caller bearer on transcode reconstruct

The authless HLS transcode delivery routes (master.m3u8 / segment) treat
the session UUID as the bearer credential, so a real request carries
requestUserID == 0. The live serve path already allows this, but
ReconstructSession hard-rejected a zero caller, so a request that worked
before a restart became SessionMissing -> 404 after the in-memory session
was gone, breaking the restart resilience these routes advertise.

Match the live-path contract in LoadOrReconstructSession: allow a zero
caller (UUID-as-bearer) and refuse only a non-zero caller that mismatches
the card owner. The reconstructed session is bound to card.UserID either
way. Adds TestReconstructSession_Ownership covering both cases.

* fix(jellycompat): re-persist recipe on local audio switch

A Jellyfin client switching audio on an integrated/local compat transcode
restarted live ffmpeg with the new track but did not re-persist
PlaybackSession.Recipe. The remote branch already re-persists via
startRemoteTranscode -> persistTranscodeRecipe. After a central restart,
reconstruct rebuilt ffmpeg from the stale Recipe.AudioTrackIndex, so the
integrated session resumed on the original audio track.

Persist the updated recipe (best-effort) after a successful Restart in the
local branch, mirroring the remote branch, so the durable
Recipe.AudioTrackIndex tracks live ffmpeg. Adds a regression test.

* fix(playback): strip stream token from proxied transcode-node URL

proxyToTranscodeNode appended the client's raw query string to the internal
transcode-node URL and logged that URL on transport failure. When a remote
transcode runs without a separate proxy node, that query carries
?st=<signed JWT> — a 24h bearer reconstruction descriptor exposing the
media path and recipe claims — placing the token into internal requests and
error logs.

Strip the "st" param before building targetURL, preserving any other query
params. The token is neither forwarded to the node nor present in the
logged URL. Header-forwarding of the token (so the node can reconstruct) is
a separate follow-up (Silo-Server#6).

* fix(playback): fail open on transient limit-provider error in reconstruct

During the reconstruct wave right after a restart (Postgres under peak
load), a transient limit-provider DB error was collapsed into a hard 404,
permanently stopping playback for a user within their limits. limitsForUser
wrapped any provider error, RegisterReconstructedWithLimits propagated it,
and ReconstructSession mapped every error to SessionMissing -> 404 -
indistinguishable from a genuine over-cap rejection.

Distinguish the two: tag provider errors with a new ErrLimitProviderUnavailable
sentinel and, during reconstruct, fail OPEN on a provider error (admit via
RegisterReconstructed + log a degraded warning) rather than refuse - mirroring
the reliability-first fail-open-on-dependency-error philosophy. A genuine
ErrTooManyStreams / ErrTooManyTranscodes over-cap still refuses. Adds tests
for both the fail-open and still-refused paths.

* fix(playback): forward stream token to transcode node as header

The dedicated transcode node's reconstruct path reads the stream token only
from the X-Silo-Stream-Token header, but proxyToTranscodeNode forwarded only
the node-API bearer token (and Silo-Server#5 now strips st from the URL). So when the
central API proxied to the node and the node self-restarted, it could not
reconstruct from the recipe-complete native token -> 404.

Capture st before stripping it from the URL, verify it at the API boundary
(streamtoken.Verify + SessionID match, mirroring the node's own check), and
forward it as X-Silo-Stream-Token. Best-effort: a missing/invalid token never
blocks the live proxy, and the token is still kept out of the forwarded URL
and logs.

* fix(playback): restart node ffmpeg on native remote audio switch

A native audio-track switch on an offloaded/remote transcode was a no-op at
the node yet returned 200 with a fresh URL: HandleChangeAudioTrack restarted
ffmpeg only when the API owned a LOCAL TranscodeSession, so for an offloaded
transcode the node kept serving the OLD audio (the node consults the token
only on a session miss). The replacement URL was also minted from identity-
only claims, so a later node restart 404'd.

For the offloaded transcode case (detected via session.TranscodeNodeURL),
POST a fresh /transcode/start to the node with the new AudioTrackIndex
(handleStart tears down and restarts ffmpeg) and mint the replacement proxy
URL from a full RecipeCard so reconstruct survives a node restart. The encode
recipe is derived from the durable session target fields plus the file,
mirroring HandleStartTranscode. A concrete SegmentDuration
(playback.DefaultSegmentDuration) is embedded rather than 0: the node's token
completeness gate treats SegmentDuration<=0 as incomplete and falls back to a
recipe store the native path never populates, which would 404 on a node
restart - the exact resilience this path provides. A failed node POST now
surfaces 502 rather than a false 200. Remux and non-offloaded (local)
transcode paths keep their prior identity-claim URLs unchanged.

Known limitation: Session does not persist the original SegmentDuration or
SubtitleTrackIndex/SubtitleBurnIn, so a remote audio switch resets subtitle
selection to none and assumes the default segment length; a client that
started with a non-default segment length will resegment on switch. Making
that state durable on the session is a follow-up.

* docs(playback): scrub stale deny-lease/revalidator comments

The deny-lease revocation mechanism and its "central revalidator" were removed
earlier in this branch, but four comments still described them as live
(transcode_manager.go, noderecipe/store.go, streamtoken/token.go,
proxy/server.go). Reword them to match the shipped behavior: ownership claims
are re-resolved at reconstruct, the noderecipe store shares Redis only with the
node-session tracker, and a sub-TTL hard cut depends on a node-side revocation
mechanism that is deferred to a future PR.

* fix(jellycompat): surface durable playback-session write failures

DurableCompatPlaybackStore.Update applied the in-memory mutation and then
swallowed every Postgres commit-failure path, returning nil. Callers that
promise restart resilience (persistTranscodeRecipe's recipe write, the
upstream-session binds in streams.go) were told the session was durably
persisted when only the cache held it, so a transient DB hiccup could leave
the next restart reloading a stale row (wrong audio track) or 404ing.

updateDB now returns the genuine DB round-trip error (begin/query/unmarshal/
marshal/exec/commit); Update propagates it while still applying the in-memory
mutation so live state stays correct. A nil pool and a genuinely absent/expired
row remain best-effort (return nil) — only real infrastructure failures
propagate, so existing rollback paths fire exactly when durability is lost.

Part of Silo-Server#174

* fix(playback): re-inject stream token into proxied transcode manifests

API-proxied remote transcode manifests dropped the reconstruct token from
their segment URLs, so playback died after a node or API restart. When a
remote transcode has no separate proxy node, the client loads its manifest via
the API-local path; proxyToTranscodeNode strips the signed token ("st") from
the forwarded URL (keeping it off node URLs and logs, forwarded only as the
X-Silo-Stream-Token header), and the node builds relative segment URIs from
that token-less query. The segment URLs the client received carried no token,
and the proxy only re-attached the header when an incoming segment request
already had "st" — which it never did — so a restart made those segments
non-reconstructable and they 404'd.

proxyToTranscodeNode now rewrites the manifest body at the boundary: every
segment and #EXT-X-MAP init URI gets the client-facing, API-verified token
re-appended (new playback.AppendManifestQueryParam helper), so the client's
later segment fetches carry "st" again and reconstruct after a restart. The
token still never reaches the node URL or its logs. Only 200 .m3u8 responses
are rewritten (Content-Length corrected); segments stream through untouched.

Part of Silo-Server#174

* fix(playback): preserve subtitle/cadence recipe across offloaded audio switch

Switching audio on a remote (offloaded) transcode with burned-in subtitles
silently dropped them, and reset a non-default segment cadence. The offloaded
audio-switch restart rebuilt the node start request from Session state, but
Session/SessionStreamState retained no subtitle or segment-duration state
(only the live local ts.Opts() and the RecipeCard did), so the branch
hard-coded SubtitleTrackIndex:-1, SubtitleBurnIn:false and
SegmentDuration:Default — signing that altered recipe into the replacement
stream token. An audio switch then changed bytes beyond audio selection, and
any later reconstruct kept the wrong no-subtitle/wrong-cadence recipe.

Persist the byte-affecting recipe on the session: SubtitleTrackIndex,
SubtitleBurnIn and SegmentDuration are added to Session/SessionStreamState,
populated at start (finalizeTranscodeStart) and on post-restart reconstruct
(ReconstructSession from the card), carried forward on every audio-switch
state update, and read back when rebuilding the offloaded node request and its
recipe card. The restart now reproduces the exact live stream. Also resolves
the M-4b non-default segment_duration reset.

Part of Silo-Server#174

* fix(playback): serialize transcode spawn paths with a per-session lock

Reconstruct was single-flighted only against other reconstructs, so a
restart-driven segment reconstruct racing a quality/seek/audio fresh start
could spawn two ffmpeg processes writing the same output directory at once —
segment corruption, partial-write closes, orphaned processes, and skewed
active-job accounting. The atomic register-after-spawn (GetOrRegister / the
reconstruct compare-on-register) prevented a map leak but not the concurrent
disk writers, because the losing path had already spawned. The dedicated
transcode node had the same split between handleStart and spawnReconstruct.

Add a refcounted per-session lifecycle lock to both TranscodeManager and the
node Server, held across "check existing -> spawn -> register":
- reconstruct (doReconstructTranscode / spawnReconstruct) re-checks under the
  lock and yields to any live session instead of spawning a duplicate;
- the native and jellycompat fresh-start paths take the lock around their
  spawn+register (the native path also closes any session a reconstruct rebuilt
  in the meantime so its fresh ffmpeg is the sole writer);
- the node handleStart holds it across teardown+spawn+register.
The refcount drops the map entry once no path holds/waits, keeping it bounded.
GetOrRegisterTranscodeSession is removed — the lock supersedes it and keeping a
register-after-spawn primitive would invite reintroducing the race.

Part of Silo-Server#174

* fix(playback): serialize restart re-spawn under the session lifecycle lock

TranscodeSession.Restart() releases s.mu across cancel -> wait-for-done ->
re-exec and spawns ffmpeg into opts.OutputDir without holding the per-session
lifecycle lock. LockSessionLifecycle's contract (fresh start, restart,
reconstruct) requires restart to hold it too, but all five callers invoked
Restart unlocked: native audio-switch and segment-recovery, compat
audio-switch and segment-recovery, and the transcode-node segment-recovery.

A restart racing another restart (audio-switch vs segment-recovery) or a
fresh-start/reconstruct could land two ffmpeg processes writing the same
segment directory -- mixed timelines, init.mp4/segment mismatch, and an
orphaned-but-still-writing ffmpeg -- the exact concurrent-writer corruption
the lifecycle lock exists to prevent.

Add RestartSessionLocked (TranscodeManager) and restartSessionLocked (node
Server) that hold LockSessionLifecycle only across the cancel->respawn
transition, re-check that the handle is still the live mapped session under
the lock, and return ErrSessionSuperseded rather than re-spawning a stale
handle. Route all five call sites through them. The lock is released before
callers wait on segments so recovery latency is unchanged.

Tests: gating (restart blocks until the lifecycle lock frees, then spawns),
concurrent-restart serialization, and superseded re-check on both the manager
(covers native + compat) and node lock owners.

---------

Co-authored-by: Quick <[email protected]>
CoffeeKnyte added a commit that referenced this pull request Jul 31, 2026
…accurate

Five defects in revocation state and credential semantics. Lands after the
tracker-lifecycle batch on purpose: raising the over-cap TTL is only safe once
the count feeding it is trustworthy.

#13 -- a longer old revocation suppressed a newer cutoff. applyLocal kept or
replaced the WHOLE record by expiry, so when the existing revocation expired
later the new one was dropped entirely, including its newer RevokedAt. The
durable upsert did the same, with a comment documenting it as intentional.
RevokedAt is the user-kill CUTOFF, so this left a credential issued between the
two cutoffs valid -- a second admin kill after a user re-authenticates silently
failed to cut them. The two fields now merge independently: ExpiresAt stays
monotonic, RevokedAt advances to the later value, and reason follows the newer
cutoff. Both superseded comments are replaced rather than left contradicting the
code. Session-kind revocation still ignores RevokedAt, so the enforcer's
re-revoke cannot weaken a session kill.

Also fixed while here: Redis received the merged record but pub/sub published the
raw input one, so under pub/sub-only delivery (Redis down) an edge got the newer
short record without the older long expiry and lost monotonicity. Both now carry
the merged record.

#7 + M1 -- Postgres could indefinitely block the urgent Redis kill.
RevokeWithWarnings held the global opMu across all propagation, stripped the
caller's deadline with WithoutCancel, and did the durable Postgres upsert BEFORE
Redis, on a pool with no statement timeout. The local kill still applied, so
playback on that process was fine -- but edge propagation, pub/sub, the admin
response and every later revoke/unrevoke stalled behind the lock. Redis and
pub/sub now go first, and the detached context is bounded. WithoutCancel is kept
deliberately: propagation must outlive an aborted admin request.

opMu scope is deliberately NOT narrowed. mirrorToRedis is an unconditional SET
with no atomic merge, so same-process serialization is what stops an older value
overwriting a newer one; narrowing the lock would also let an unrevoke interleave
with a revoke's propagation. Bounding the context caps how long the lock can be
held, which is the actual reported harm. The remaining cross-replica race -- two
central replicas racing the same SET -- is documented, not half-fixed; it needs
A6's shared picture.

A2 / #6 -- a missed unrevoke got resurrected. In-memory tombstones already
existed, but being process-local they did not survive a restart or reach a
replica that missed the pub/sub event, so maintain's durable self-heal
re-Upserted the surviving entry and the ban returned. Tombstones are now durable,
via two nullable columns on stream_revocations rather than a second table: a
tombstone is a state of the same key, and it needs its own expiry horizon
separate from the revocation's. The upsert rejects a stale replica's write while
a tombstone is live but lets a genuinely newer revocation clear it, and warm
paths apply tombstones BEFORE revocations so an un-banned key cannot be restored
as a live kill. Tombstones are pruned on the same sweep, so the table cannot grow
without bound.

A1 / #3 -- over-cap kills reopened after 5 minutes while the token stayed
reconstructable for 24h. The TTL now derives from playback.MaxTokenTTL rather
than duplicating 24h, behind a validated setting.

Critically, the enforcer uses a revoke-if-absent path rather than re-revoking.
Expiry is monotonic and the enforcer re-evaluates every 30s, so a plain long TTL
would slide expiry forward by another full lifetime on every pass -- making a
wrong kill effectively permanent for as long as any stale record persisted, with
only an explicit unrevoke to recover it. Admin Revoke keeps its monotonic
behaviour; only the enforcer's own repeat kill is non-extending. The setting is
documented as affecting future revocations only, since monotonic expiry means it
cannot shorten one already issued.

A3 / #5 -- the user cutoff compared against a fresh time.Now() taken at request
entry, so a request from a pre-cutoff login could look post-cutoff and escape the
kill. The credential time is now the access token's iat.

Two deliberate choices worth stating. API-key credentials carry no issue time, so
they pass the zero time and, per IsRevoked's documented contract, are never
matched by a user cutoff: a user kill provably cannot cut an API-key-owned pour.
That is an accepted, logged, documented hole -- and strictly better than
time.Now(), which actively defeats the cutoff. And jellycompat uses the compat
session's CreatedAt rather than the bridged Silo token's iat, because that token
refreshes without a new Jellyfin login, so its iat would advance on refresh and
let a refreshed credential slip past a cutoff.

Stream tokens are now bound to their route: a token whose SessionID does not match
the URL's session_id is rejected with 403 instead of being silently ignored,
matching the reconstruction helper that already refused a different session.

Per-login logout cuts remain out of scope -- they need per-login identity in the
stream credential. S5 (the (sessionID, userID, startedAt) clump) is rejected as
ceremony now that A3 is the iat option rather than the generation model.

#12 (closing an RSS feed does not cut its current pour) is deferred: it needs a
namespaced revocation id that cannot collide with real session ids, that id
threaded onto public feed requests, and protection against a new feed inheriting
an old tombstone.

Part of #305.
CoffeeKnyte added a commit that referenced this pull request Jul 31, 2026
…mits

Marks #13, #7/M1, A2/#6, A1/#3 and A3/#5 resolved, and records the limits this
batch accepts rather than leaving them for the next reviewer to rediscover.

Retracts the last of the two false claims flagged in the serve-path docs pass:
the kill switch now does "keep a stream dead" for the token's reconstructable
life. The other -- monitoring does not "never trust client progress" -- is still
false and stays flagged until decision A5 lands.

Newly documented accepted limits:

- A user cutoff cannot cut an API-key-owned pour. API-key credentials carry no
  issue time, so they take the zero credential time and IsRevoked's documented
  fail-open contract applies. Deliberate, logged, and better than substituting
  time.Now(), which actively defeats the cutoff.
- Two central replicas revoking the same key can still race the Redis mirror,
  because mirrorToRedis is an unconditional SET rather than an atomic merge.
  Same-process writes are serialized by opMu; cross-replica convergence needs
  A6's shared picture.
- The over-cap TTL setting affects future revocations only. Monotonic expiry
  means it cannot shorten an existing kill; only an explicit unrevoke clears one,
  and the enforcer may recreate it while the over-count persists.
- Per-login logout cuts are still unavailable: cutting one device's live streams
  needs per-login identity in the stream credential, which is the
  authorization-generation model rather than the iat model chosen here.

Records that the enforcer's repeat kill is non-extending and why: with monotonic
expiry and a 30s evaluation loop, a plain long TTL would renew a wrong kill
indefinitely for as long as any stale record survived.

Part of #305.
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.

1 participant