Skip to content

perf(jellycompat): resolve the viewer access scope once per request - #2959

Merged
Quick104 merged 1 commit into
Silo-Server:mainfrom
blurbery:perf/jellycompat-request-access-scope
Oct 23, 2026
Merged

Quick104 merged 1 commit into
Silo-Server:mainfrom
blurbery:perf/jellycompat-request-access-scope

Conversation

@blurbery

@blurbery blurbery commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none. No passed case reaches this path; #1246 C1 and C2 (Jellyfin compatibility, not run yet) will exercise it.

Requests from Jellyfin apps (Infuse, Swiftfin, Kodi, Jellyfin Web) do more database work than they need to. Each catalog read in a jellycompat handler resolves the viewer's access scope again, at four Postgres statements and a policy evaluation each for a default profile. Opening an episode resolves it three times (the episode, its series' artwork, its season), and an episode list with Fields=MediaSources,MediaSourceCount five times. This change resolves it once per request.

For context, on a production deployment the jellycompat /Users/{id}/Items routes had a p95 of about 1.4 s over 72 hours, and the "access scope resolution failed" warning fired 225 times in the same window. That warning also fires at WARN when the client has already hung up (context canceled).

Approach

The compat session middleware (serveWithSessionContext) now gives each request a holder for the resolved scope. The resolver behind the access filter (NewScopeAccessFilter) and the playback bitrate cap (PlaybackScopeResolver) both use it. A call whose resolve input is the session viewer's own (UserID, ProfileID, SkipPINVerification) resolves once and gets the scope from the holder after that. Anything else resolves exactly as before: another profile on the same account, a different input such as ContentAccessOnly, or code running outside an authenticated compat request.

  • Every caller gets its own copy of the library lists and the language overrides, so nothing a caller does to its filter reaches the next one. Copies keep nil and empty apart, since a nil allowlist grants every library and an empty one grants none.
  • A failed resolution is not kept. Each failing call still fails closed on its own and the next call tries again, as today.
  • Nothing outlives the request and nothing is shared between requests or replicas. A revoked library, a profile change, or a policy edit applies from the next request on, which is the property Cut the per-request identity prelude to two round trips #1389 keeps for the native prelude.
  • It wraps the resolver rather than AccessFilterFn, because withDefaults wraps AccessFilterFn on each of its two passes in production. The resolver wrapper is idempotent and leaves an unset PlaybackScopeResolver nil.
  • The failure warning now goes through ctxerr.LogLevel, so a client that disconnected mid-resolution logs at debug instead of warn.

Only internal/jellycompat changes. Responses are unchanged, so the clients and the manual need nothing, and the native API already resolves the scope once per request in RequireViewerAccess.

Validation

  • Unit tests (go test ./internal/jellycompat/, no database): pass. New ones cover one resolution per request through the real middleware, a second request resolving again, edits to a returned filter not reaching later calls, another profile or another input resolving on its own, a failure not being kept, and nil and empty allowlists keeping their meaning. A reflection check fails if a top-level slice, map or pointer field is added to access.Scope without being copied.
  • DB pin TestCompatEpisodeItemResolvesScopeOnceDB (added to scripts/ci/db-pins.txt): drives the two requests above through the compat router, the catalog repositories and the production policy viewer resolver. It fails on main (3 resolutions for the episode) and passes here. It also checks the episode still comes back with its series and season.
  • The whole package against a freshly migrated local Postgres 18 database: pass.
  • gofmt and go vet on the package: clean. I did not run make lint-changed locally; CI lints the changed lines.
  • CI on 60b755b: Go test, Go lint, Go DB pins (including the new pin), Go integration, Go DB external auth and the repository checks passed (https://github.com/Silo-Server/silo-server/actions/runs/39879851176). The Web jobs were not selected.

Benchmarks

Request Statements, main > this PR Scope resolutions Time per request (local)
GET /Users/{id}/Items/{episodeId} 42 > 34 3 > 1 1.90 ms > 1.51 ms (−21%)
GET /Users/{id}/Items?ParentId={seriesId}&IncludeItemTypes=Episode&Recursive=true&Fields=MediaSources,MediaSourceCount 39 > 23 5 > 1 1.83 ms > 1.00 ms (−45%)
How these were measured
  • Baseline: main at 8c90021. Changed: 60b755b. The baseline runs used this branch's test file with main's sources.
  • Workload: the pin's fixture: one account with a default profile in no access group, one series library, one series with one season and one episode, and the production policy.ViewerResolver and catalog repositories behind the compat router. The statement counts come from a pgx tracer on the pool and were identical in every run.
  • Command: SILO_TEST_DATABASE_URL=… go test -run '^$' -bench CompatScopeOnce -benchtime=2s -count=2 ./internal/jellycompat/, three rounds per side alternating main and this branch (6 runs each), compared with benchstat. Both differences are p=0.002, n=6.
  • Environment: Apple M5 Pro laptop, Postgres 18.6 on loopback, Go 1.27.1 with GOMAXPROCS=6, no other load.
                                     │   main    │            this PR             │
                                     │  sec/op   │   sec/op     vs base           │
episode_detail-6                       1.898m ± 3%  1.507m ± 4%  -20.61% (p=0.002 n=6)
episode_list_with_media_sources-6      1.832m ± 4%  1.001m ± 4%  -45.32% (p=0.002 n=6)

Limitations: one client on a loopback database with no other load, so the times leave out network round trips and pool waits, which is where fewer statements help most on a busy server. I did not measure a viewer in an access group, whose resolution also reads the group's policy, or PlaybackInfo, which now shares one resolution between the item detail and the bitrate cap.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/pr-2959/

Surface and build: the Jellyfin compat API, the two requests in Benchmarks, served by the compat router over a local test database. Before: main at 8c90021. After: 60b755b. The response bodies are byte for byte the same on both builds; the page has both, with the statement and scope-resolution counts for each. Nothing a client shows changes.

Risks

  • Within one request, every read now sees the scope as it was at the first read. Before, a policy edit that landed mid-request could reach the later reads of that request. The next request sees it either way.
  • Concurrent reads in one request could each resolve once before the first result is kept, as every read did on main. No call site reads the scope concurrently.
  • Long-lived requests (direct streams, downloads) already resolve once at the start; none re-checks access mid-request, so none loses a revocation it used to see.
  • perf(jellycompat): page BoxSet children in SQL #2616 adds a resolveAccessFilter call in handlers_collections.go; it picks this up without changes.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code (desktop app)
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: AI-assisted with Claude Opus. I directed the task and designed the work.
  • Adversarial review: a separate Claude Code agent (claude-opus-5-5) reviewed the complete diff against main, read-only. It checked behaviour parity at every caller of the access filter and the bitrate cap, profile versus account and access-group scoping, nil versus empty allowlists, error handling, concurrency, multi-replica state, and the tests. It also ran mutation tests: breaking the copies, the per-request lifetime, the input check, or the no-failure rule each made a test fail. It found no correctness or security problems. Its low-severity findings were a lock held across the inner resolution (a deadlock if a wrapped resolver were ever wrapped again), the bitrate cap building its own resolve input, and some test and comment wording. All of those are fixed.

@silo-kody

silo-kody Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

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

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

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@coderabbitai

coderabbitai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

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

Next included review available in 2 minutes.

Check out review usage here.

View limit details

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

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ae391136-7f8a-4a4a-9715-24c843c2860f
📥 Commits

Reviewing files that changed from the base of the PR and between e91d680 and 5bb6c3a.

📒 Files selected for processing: 7
  • internal/jellycompat/access_filter.go
  • internal/jellycompat/access_filter_test.go
  • internal/jellycompat/auth.go
  • internal/jellycompat/handlers_playback.go
  • internal/jellycompat/request_scope_db_test.go
  • internal/jellycompat/router.go
  • scripts/ci/db-pins.txt
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

❤️ Share

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

@silo-triage silo-triage Bot added the size/XL 500–999 added + deleted lines (all files); change volume, not priority. label Oct 23, 2026
@macroscopeapp

macroscopeapp Bot commented Oct 23, 2026

Copy link
Copy Markdown

The request-scoped scope cache can change which nested items or playback availability a Jellyfin response includes if library access or policy changes while the request is in progress. The Evidence section says there is no user-visible change and provides no evidence for this case. Please add before-and-after API response excerpts for the same compat request with an access-policy change between scope lookups, naming the surface and commit.

Suggested fix: No diff — add the matching before-and-after response excerpts under Evidence.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@silo-triage silo-triage Bot added enhancement New feature or request go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels Oct 23, 2026
@blurbery

Copy link
Copy Markdown
Contributor Author

That case is the one under Risks, and it isn't a change a client can see in normal use. Before this PR, a policy edit that landed between two scope lookups in the same request could build one response from two different scopes, say the episode under the old one and its season under the new one. Now the whole response uses the scope from the first lookup, and the next request picks up the edit, as it did before.

When nothing is edited mid-request, which covers every request the new pin and the existing jellycompat tests drive, the response is the same as on main. So there is no before-and-after pair to capture for it.

@Quick104

Copy link
Copy Markdown
Contributor

Review summary (head 60b755b)

No changes needed. I found no defect in this PR and pushed nothing.

What I checked. The cache lives in a holder that serveWithSessionContext creates fresh for each authenticated request. A call reads from it only when its whole access.ResolveInput equals the session's own (account, profile, SkipPINVerification, and the zero SessionID, ProfileToken and ContentAccessOnly). Any other profile, account or input resolves as before. In production, cmd/silo/main.go passes the same resolver to NewScopeAccessFilter and PlaybackScopeResolver in both the policy and legacy branches, so the two consumers can't hand each other a scope from a different policy. cloneScope copies all four reference fields of access.Scope; the embedded MaturityLimits holds only scalars. Failures are not cached and still deny every library. The bitrate cap still picks local or remote after the scope is read. The WebSocket handler and the detached-context goroutines in streams.go never resolve a scope, so nothing holds a cached scope past its request. ctxerr.LogLevel lowers the warning to debug only when the context was canceled and every error in the chain is a cancellation.

Tests. TestCompatEpisodeItemResolvesScopeOnceDB fails on the base for the reason it claims (the episode detail resolves the scope 3 times, the episode list 5) and passes on the head, against a freshly migrated pgvector Postgres 18. The new unit tests in access_filter_test.go don't build on the base because they call the new helpers, so the DB pin is the test that proves the change. make lint-changed, verify-size-ratchet, verify-bidi and verify-local-paths pass with this branch merged into current main.

Related jellycompat PRs. I merged main with this PR, #2960, #2949 and #2956. The only conflict is with #2960, in scripts/ci/db-pins.txt: both PRs append a pin at the same spot, and keeping both lines resolves it. The combined tree builds, and the whole internal/jellycompat package passes with the database, including both new pins. The order doesn't matter beyond the second PR needing that one-line rebase.

Minor notes, no action needed.

  • Two concurrent first lookups in one request could both resolve. The PR lists this under Risks, and no handler looks up the scope concurrently today.
  • The cache is keyed on the request, not on the inner resolver. Wiring AccessFilterFn and PlaybackScopeResolver to different resolvers would make them share one scope. Nothing does that today.
  • TestCloneScopeCopiesReferenceFields checks only top-level fields, so a slice later added to MaturityLimits would get past it.

Second opinion. A read-only Codex review (gpt-6.1-sol) of the same diff found no authorization problems. It confirmed that PIN login, admin keys, PlaySessionId and static stream grants keep their identity checks.

Validated features. None reached. The only passed cases on the board are for person browsing (#1143), which uses the native API. #1246 (Jellyfin compatibility) has no recorded passes yet. A comment there reports C2 passing on base; its forbidden-item checks run through the access filter this PR caches, and the restriction logic is unchanged. Validation tasks: none in the body is correct.

User manual: unaffected (no setting, default or visible behavior changes). Apple/Android: no client change; responses are unchanged.

Fit: 9/10 · Readiness: 9/10 — ready

Fit: it removes repeated database work for Jellyfin clients and resolves the scope once per request, as the native API already does in RequireViewerAccess. Nothing outlives the request or crosses replicas. Readiness: no open concern, and the DB pin fails on the base and passes on the head.

Reviewed with Claude Code (claude-opus-5-5), with a cross-provider check by Codex (gpt-6.1-sol).

Every catalog read in a Jellyfin request resolved the viewer's access scope
again: an episode's detail resolved it three times (episode, series artwork,
season) and an episode list with media sources five times, each with its own
Postgres reads and policy evaluation.

The compat session middleware now gives each request a place to keep the
resolved scope. The access filter and the playback bitrate cap resolve the
session viewer's scope once per request and hand every caller its own copy
of the library lists. Other inputs resolve as before, failures are not kept,
and the next request resolves again, so revocations and policy edits still
apply from the next request on.

A client disconnect during resolution now logs at debug instead of warn.
@Quick104
Quick104 force-pushed the perf/jellycompat-request-access-scope branch from 60b755b to 5bb6c3a Compare October 23, 2026 19:46
@Quick104

Copy link
Copy Markdown
Contributor

Rebased onto main and kept both scripts/ci/db-pins.txt entries after #2960 merged.

@silo-kody

silo-kody Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

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

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

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@macroscopeapp

macroscopeapp Bot commented Oct 23, 2026

Copy link
Copy Markdown

Minor change — #1246 C1 and C2 now have recorded runs on the changed Jellyfin path. The October 23 task update records them on a local integration build based on 31fabc723 plus #2934, #2935 and #2970. C1 covers browse/play; C2 covers restricted library and item access, PlaybackInfo, streams, downloads and subtitles. This PR makes those paths reuse one access scope per HTTP request, reducing repeated resolution and latency. Please mark both for re-check after merge and replace the stale line with:

Validation tasks: changes #1246 C1 and C2

Suggested fix: No diff — update the Validation tasks: line in the PR description.

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

Posted via Macroscope — v1 validation impact

@Quick104
Quick104 merged commit 087aaf2 into Silo-Server:main Oct 23, 2026
16 checks passed
@blurbery
blurbery deleted the perf/jellycompat-request-access-scope branch November 6, 2026 00:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/XL 500–999 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants