Skip to content

feat(jellycompat): support Autoscan via Jellyfin media-update endpoint - #8

Merged
Quick104 merged 9 commits into
mainfrom
t3code/jellyfin-autoscan-scan-compat
May 26, 2026
Merged

Quick104 merged 9 commits into
mainfrom
t3code/jellyfin-autoscan-scan-compat

Conversation

@Quick104

@Quick104 Quick104 commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add POST /Library/Media/Updated route in jellycompat that resolves changed paths to libraries and enqueues scans via a shared scan trigger resolver (all-or-fail across multi-update requests)
  • Augment GET /Library/VirtualFolders to return real Locations for enabled libraries when called with an admin API key, falling back to the existing items-handler response for normal sessions
  • Accept Silo admin API keys (sa_) on the new Autoscan routes (X-Emby-Token, X-Mediabrowser-Token, Authorization: Bearer, api_key) so Autoscan's stock Jellyfin target can authenticate
  • Extract scan target/trigger resolution into internal/scantrigger and reuse it from the existing libraries API
  • Add scanqueue.Service.EnqueueScans + Repository.CreateBatch for transactional batch enqueue
  • Document the Autoscan + Jellyfin compat setup in docs/scan-api.md and add the design spec under docs/superpowers/specs/

Testing

  • go test ./internal/jellycompat/... ./internal/scantrigger/... ./internal/scanqueue/... ./internal/api/handlers/...
  • make lint
  • Manual: point Autoscan's Jellyfin target at the compat URL with an sa_ token and confirm GET /Library/VirtualFolders + POST /Library/Media/Updated trigger scans

Note

Medium Risk
Touches Jellyfin auth routing and scan enqueue paths; admin-only API keys limit blast radius, but misconfigured Autoscan could trigger many subtree/file scans on the compat port.

Overview
Adds Jellyfin compatibility for Autoscan’s stock Jellyfin target so download automation can discover libraries and trigger scans without a custom script.

On the compat server, GET /Library/VirtualFolders returns real filesystem Locations for enabled libraries when authenticated with an admin sa_ API key (Jellyfin session tokens still use the existing handler). POST /Library/Media/Updated accepts Autoscan’s Updates[] payload, resolves paths with the same rules as the native scan API, and enqueues scans with all-or-fail validation across multiple updates. Admin API keys are accepted via the usual Jellyfin token headers; non-admin keys are rejected.

Scan path resolution is extracted to internal/scantrigger and reused by POST /api/v1/scan and the new compat handler. The scan queue gains transactional batch enqueue (CreateBatch / EnqueueScans). docs/scan-api.md and a design spec document the Autoscan setup.

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

Summary by CodeRabbit

  • New Features

    • Stock Autoscan support via Jellyfin-compat endpoints (virtual folders + media-updated) using admin API keys.
  • Improvements

    • Admin API-key authentication for compatibility endpoints.
    • Unified scan target resolution with clearer validation and all-or-fail batch enqueueing to avoid partial processing.
    • Batch scan enqueueing to reduce duplicate work.
  • Documentation

    • Updated Autoscan setup docs with Jellyfin-compat URL and admin API-key guidance.
  • Tests

    • Added coverage for Autoscan flows, admin-key auth, resolver logic, and batch enqueue behavior.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d226c993-f5c0-4944-9d9f-3ecbd80f2c1d

📥 Commits

Reviewing files that changed from the base of the PR and between eccf68f and 2bf9651.

📒 Files selected for processing (2)
  • internal/jellycompat/handlers_autoscan.go
  • internal/jellycompat/handlers_autoscan_test.go

📝 Walkthrough

Walkthrough

Adds Autoscan Jellyfin compatibility: new scantrigger package for resolving/enqueuing scans, admin API-key auth, Autoscan endpoints (VirtualFolders, Media/Updated), router/server/main wiring, native scan handler refactor to reuse the resolver, scanqueue batch enqueue support, tests, and docs.

Changes

Autoscan Jellyfin Compatibility

Layer / File(s) Summary
Scan trigger resolution package
internal/scantrigger/scantrigger.go, internal/scantrigger/scantrigger_test.go
New package provides Resolver for validating scan requests, resolving target libraries by ID or path matching, classifying paths (library/subtree/file), normalizing triggers, and returning structured RequestError on validation failure. Includes EnqueueAll for batch all-or-fail enqueuing and helper functions for path/root matching. Tests verify classification modes, disabled library rejection, and all-or-fail/batch enqueue behavior.
Admin API key authentication
internal/jellycompat/auth_api_key.go, internal/jellycompat/auth_test.go
Introduces AdminAPIKeyAuthenticator middleware that validates sa_-prefixed admin API keys, enforces enabled admin user role, and marks authenticated requests via context. Provides RequireAdminAPIKey enforcement and conditional RequireSessionOrAdminAPIKey routing that demultiplexes by token prefix. Tests verify admin and non-admin user handling, missing-key handling, and last-used update deadline behavior.
Autoscan handlers and endpoints
internal/jellycompat/handlers_autoscan.go, internal/jellycompat/handlers_autoscan_test.go
Implements AutoscanHandler with two endpoints: GET /Library/VirtualFolders returns enabled library locations (requires admin API key), and POST /Library/Media/Updated validates update paths and enqueues scans via scantrigger with all-or-fail batch semantics. Tests verify virtual folder listing, successful enqueue with resolved mode/path/trigger, all-or-fail rejection on invalid paths, and error masking for internal queue failures.
Scan queue batch creation & service
internal/scanqueue/repository.go, internal/scanqueue/service.go
Adds Repository.CreateBatch to insert-or-reuse multiple scan runs in a transaction and Service.EnqueueScans to convert scantrigger.Target slices into batch create inputs, publish scan.accepted events for created runs, and return errors for batch creation failures. Tests assert batch enqueue uses a single batch queue call.
Server, router, and main wiring
internal/jellycompat/server.go, internal/jellycompat/router.go, cmd/silo/main.go
Extends Dependencies struct with API key validator, user loader, and scan queue fields. Router conditionally wires autoscan handler with admin API key auth when dependencies are present, registering /Library/VirtualFolders (GET) and /Library/Media/Updated (POST) and preventing duplicate virtual-folder routing. cmd/silo/main.go supplies the API key repo, user loader, and library scan queue to compat dependencies.
Native scan handler refactoring
internal/api/handlers/libraries.go
Refactors HandleScan to delegate resolution to scantrigger.NewResolver(...).Resolve(...) instead of local resolveScanTarget logic. Removes local scan-mode types and path-matching helpers. Updates scan queueing and ingester dispatch to use target.Mode, target.Path, target.LibraryID, target.Trigger. Changes recordAcceptedScan to accept *scantrigger.Target and upsert using target fields.
Design specification and documentation
docs/superpowers/specs/2026-05-24-jellyfin-autoscan-scan-compat-design.md, docs/scan-api.md
Adds design spec defining Autoscan-Jellyfin compatibility goals (Jellyfin only), current Silo gaps, required endpoints, admin API key authentication, library discovery, scan notification validation with all-or-fail semantics, error handling, testing scope, and component boundaries. Updates user docs to describe stock Jellyfin target usage (URL, sa_... token, server-side paths) and keeps the custom-script alternative.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped through code and tunnels deep,

sa_ tokens wake from quiet sleep,
VirtualFolders show roots in light,
Updates queued in batches, all-or-none right,
Autoscan and Jellyfin feast tonight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.44% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(jellycompat): support Autoscan via Jellyfin media-update endpoint' accurately and concisely summarizes the main change: adding Autoscan support to the jellycompat module via a new media-update endpoint.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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/jellyfin-autoscan-scan-compat

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

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

🧹 Nitpick comments (1)
internal/jellycompat/handlers_autoscan.go (1)

145-145: ⚡ Quick win

Avoid returning raw internal errors to clients.

Line 145 exposes the raw err string in the API response. Prefer a fixed client-facing message and keep details in logs only.

Suggested fix
 	slog.Error("jellycompat autoscan: scan update failed", "error", err)
-	writeError(w, http.StatusInternalServerError, "InternalServerError", fmt.Sprintf("Failed to process scan update: %v", err))
+	writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to process scan update")
 }
🤖 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/jellycompat/handlers_autoscan.go` at line 145, The current
writeError call returns the raw err to clients; change it to return a fixed
client-facing message (e.g. writeError(w, http.StatusInternalServerError,
"InternalServerError", "Failed to process scan update")) and move the detailed
error to server logs (e.g. log.Printf or your request/logger instance)
immediately before the writeError call; update the statement that references
writeError, err, and w so the client sees only the generic message while the
real err is logged for diagnostics.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/jellycompat/auth_api_key.go`:
- Around line 85-90: The code calls a.keys.GetByKey and immediately dereferences
apiKey.UserID which can panic if apiKey == nil; update the auth path in the
function containing the GetByKey call to check for apiKey == nil (and treat it
like an unauthorized error) before calling a.users.GetByID, returning an
adminAPIKeyAuthResult with http.StatusUnauthorized when apiKey is nil or when
GetByKey returns an error, so that apiKey.UserID is only accessed after
confirming apiKey is non-nil and valid.
- Around line 96-99: The async goroutine calling a.keys.UpdateLastUsed currently
uses context.Background() with no deadline which can hang; replace that with a
cancellable context with a short timeout (e.g., via context.WithTimeout) inside
the goroutine, defer the cancel, pass the timed context to keys.UpdateLastUsed,
and keep the existing error logging (slog.Debug) so slow/stuck backends won't
block goroutines indefinitely when invoking UpdateLastUsed.

In `@internal/scantrigger/scantrigger.go`:
- Around line 149-157: EnqueueAll currently calls queue.EnqueueScan per target
which can leave partial side effects if one call fails; change the contract to
perform the enqueue atomically by adding a batch operation on the Queuer (e.g.,
EnqueueBatch or EnqueueScans) that accepts all targets at once and returns a
single error, update the Queuer interface to include that batch method, and
replace the loop in EnqueueAll with a single call to queue.EnqueueBatch(ctx,
targets) (or, alternatively, implement transaction/rollback methods on Queuer
such as BeginTransaction/Commit/Rollback and use them inside EnqueueAll) so
failures do not leave previously enqueued targets behind; update all callers and
tests to use the new batch/transaction methods.

---

Nitpick comments:
In `@internal/jellycompat/handlers_autoscan.go`:
- Line 145: The current writeError call returns the raw err to clients; change
it to return a fixed client-facing message (e.g. writeError(w,
http.StatusInternalServerError, "InternalServerError", "Failed to process scan
update")) and move the detailed error to server logs (e.g. log.Printf or your
request/logger instance) immediately before the writeError call; update the
statement that references writeError, err, and w so the client sees only the
generic message while the real err is logged for diagnostics.
🪄 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: 2781114b-2e56-4840-a17f-3389e00d880f

📥 Commits

Reviewing files that changed from the base of the PR and between 0e927b3 and 096d7976cd56960e4d2ed105d038a34b3f540d15.

📒 Files selected for processing (12)
  • cmd/silo/main.go
  • docs/scan-api.md
  • docs/superpowers/specs/2026-05-24-jellyfin-autoscan-scan-compat-design.md
  • internal/api/handlers/libraries.go
  • internal/jellycompat/auth_api_key.go
  • internal/jellycompat/auth_test.go
  • internal/jellycompat/handlers_autoscan.go
  • internal/jellycompat/handlers_autoscan_test.go
  • internal/jellycompat/router.go
  • internal/jellycompat/server.go
  • internal/scantrigger/scantrigger.go
  • internal/scantrigger/scantrigger_test.go

Comment thread internal/jellycompat/auth_api_key.go Resolved
Comment thread internal/jellycompat/auth_api_key.go Resolved
Comment thread internal/scantrigger/scantrigger.go Resolved

@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: 096d7976cd

ℹ️ 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 thread internal/scantrigger/scantrigger.go Outdated
Comment on lines +66 to +67
for _, req := range requests {
target, err := r.Resolve(ctx, req)

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 Batch-resolve scan targets with one library lookup

ResolveAll loops over updates and calls Resolve for each entry; for autoscan requests these entries are path-only, so each iteration executes folders.List(ctx) again inside Resolve. That turns a single /Library/Media/Updated batch into N full library-list DB queries, which can add substantial latency and DB load for larger batches and increases timeout risk under load. Cache the folder list once per ResolveAll call (or add a path-only bulk resolver) so batch size does not multiply repository round-trips.

Useful? React with 👍 / 👎.

Comment thread internal/scantrigger/scantrigger.go Outdated
Comment on lines +153 to +155
for _, target := range targets {
if _, err := queue.EnqueueScan(ctx, target.LibraryID, target.Mode, target.Path, target.Trigger); err != nil {
return fmt.Errorf("queueing library scan: %w", err)

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 Preserve all-or-fail behavior when enqueueing batched updates

HandleMediaUpdated validates all updates first, but EnqueueAll then enqueues each target one-by-one and returns immediately on the first enqueue failure. If a later enqueue fails (for example a transient DB error), earlier scans in the same request remain accepted while the API returns an error, which creates partial execution and retry ambiguity for clients. Batched updates should be enqueued atomically (or otherwise return explicit partial status) to avoid inconsistent behavior.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the t3code/jellyfin-autoscan-scan-compat branch from 096d797 to 7d612f6 Compare May 25, 2026 15:30

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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-jellyfin-autoscan-scan-compat-design.md`:
- Around line 32-40: The example JSON uses an absolute filesystem path in the
"Updates" array ("path" field); replace that absolute path with a neutral
repository-relative placeholder (e.g., use a repo-relative path like
"path/to/media/Show/Season 01/Episode.mkv" or a clearly marked placeholder such
as "<repo-root>/path/to/media/...") and add a short note that examples assume
the repository root is the cwd; update the JSON example under the "Updates"
array accordingly to avoid local absolute paths.
🪄 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: bbc2a081-3d1b-4199-9914-28f0de7a11ab

📥 Commits

Reviewing files that changed from the base of the PR and between 096d7976cd56960e4d2ed105d038a34b3f540d15 and 7d612f6.

📒 Files selected for processing (12)
  • cmd/silo/main.go
  • docs/scan-api.md
  • docs/superpowers/specs/2026-05-24-jellyfin-autoscan-scan-compat-design.md
  • internal/api/handlers/libraries.go
  • internal/jellycompat/auth_api_key.go
  • internal/jellycompat/auth_test.go
  • internal/jellycompat/handlers_autoscan.go
  • internal/jellycompat/handlers_autoscan_test.go
  • internal/jellycompat/router.go
  • internal/jellycompat/server.go
  • internal/scantrigger/scantrigger.go
  • internal/scantrigger/scantrigger_test.go

Comment on lines +32 to +40
```json
{
"Updates": [
{
"path": "/media/tv/Show/Season 01/Episode.mkv",
"updateType": "Modified"
}
]
}

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

Replace absolute filesystem example path with a neutral placeholder.

The JSON example uses an absolute local filesystem path (/media/...) in a spec file under docs/superpowers/specs, which violates the docs-path policy for specs/plans.

Suggested doc fix
 {
   "Updates": [
     {
-      "path": "/media/tv/Show/Season 01/Episode.mkv",
+      "path": "<server-library-path>/Show/Season 01/Episode.mkv",
       "updateType": "Modified"
     }
   ]
 }

As per coding guidelines, “When creating or editing docs/superpowers/specs/ or docs/superpowers/plans/, never include local absolute filesystem paths or transient worktree IDs; use repository-relative paths and wording like 'Commands assume the repository root is the cwd.'”

📝 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
```json
{
"Updates": [
{
"path": "/media/tv/Show/Season 01/Episode.mkv",
"updateType": "Modified"
}
]
}
🤖 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 `@docs/superpowers/specs/2026-05-24-jellyfin-autoscan-scan-compat-design.md`
around lines 32 - 40, The example JSON uses an absolute filesystem path in the
"Updates" array ("path" field); replace that absolute path with a neutral
repository-relative placeholder (e.g., use a repo-relative path like
"path/to/media/Show/Season 01/Episode.mkv" or a clearly marked placeholder such
as "<repo-root>/path/to/media/...") and add a short note that examples assume
the repository root is the cwd; update the JSON example under the "Updates"
array accordingly to avoid local absolute paths.

- Reject nil API keys and bound last-used update with a 5s timeout
- Stop leaking internal queue errors in autoscan responses
- Batch scan enqueues via new CreateBatch and reuse folder list across path resolves
}
resp = append(resp, virtualFolderDTO{
Name: folder.Name,
Locations: folder.Paths,

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.

Autoscan Locations may serialize as JSON null

Low Severity

The autoscan HandleVirtualFolders sets Locations directly from folder.Paths, which could be a nil slice, producing "Locations": null in JSON. The existing session-based HandleVirtualFolders in ItemsHandler explicitly uses []string{}, which always serializes to []. Autoscan may not handle null gracefully when comparing incoming paths against library roots.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 09a02a7. Configure here.

bestLen = rootLen
}
}
return bestRoot, 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.

Exported helpers only used within same package

Low Severity

LongestMatchingRoot, MatchFolderForPath, ClassifyPath, and PathWithinRoot are all exported but only called within the scantrigger package itself. Since the tests are also in package scantrigger (not an _test package), these functions don't need to be exported. Unexported names would better communicate their intended scope.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 09a02a7. Configure here.

- Read library ID from Target.Folder.ID everywhere
- Guard scan queue enqueue against nil Folder
- Simplify admin API key auth error plumbing

@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 3 total unresolved issues (including 2 from previous reviews).

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 eccf68f. Configure here.

Comment thread cmd/silo/main.go
userRepo := auth.NewUserRepository(deps.DB)
compatDeps.APIKeyValidator = auth.NewAPIKeyRepository(deps.DB)
compatDeps.APIKeyUserLoader = userRepo
compatDeps.ScanQueue = deps.LibraryScanQueue

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.

Nil interface trap causes wrong error for unconfigured queue

Medium Severity

Assigning deps.LibraryScanQueue (a *scanqueue.Service that may be nil) to compatDeps.ScanQueue (a scantrigger.Queuer interface) triggers Go's nil-interface trap. When the scan queue isn't configured, the interface wraps a nil concrete pointer but is itself non-nil. The h.queue == nil guard in HandleMediaUpdated then passes, causing the handler to proceed and ultimately return a misleading 500 instead of a clean 503 "Scanner not available."

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit eccf68f. Configure here.

@zZebrahz

Copy link
Copy Markdown
Contributor

I was able to add a few fixes to the existing code for it to work and made a commit @Quick104

@Quick104
Quick104 merged commit 87451d0 into main May 26, 2026
1 check passed
@Quick104
Quick104 deleted the t3code/jellyfin-autoscan-scan-compat branch May 26, 2026 12:33
Quick104 added a commit to thezak48/silo-server that referenced this pull request Jun 7, 2026
…oscan-scan-compat

feat(jellycompat): support Autoscan via Jellyfin media-update endpoint
Quick104 added a commit that referenced this pull request Jun 11, 2026
…compat

feat(jellycompat): support Autoscan via Jellyfin media-update endpoint
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]>
fluxis added a commit to fluxis/silo-server that referenced this pull request Jun 17, 2026
Silo-Server#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. (Silo-Server#9 coarse case already handled:
audiobookFolderShouldSkip skips unchanged folders; per-file reuse deferred.)

Silo-Server#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]>
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 Jul 31, 2026
… canonical

Five defects that all produced a WRONG over-cap count, which is why they land
before the revocation batch: decision A1 raises the over-cap revocation TTL from
5m to ~24h, removing the self-healing that currently limits the damage of a
miscount. A false positive after A1 blocks a legitimate stream for a day, so the
count has to be trustworthy first.

#1 -- overlapping edge requests deleted a live stream. Tracker.sessions was a
set and Remove tore down all state plus the Redis key, while both proxy pour
handlers deferred removal unconditionally. Two overlapping Range GETs on one
session id -- ordinary seek behaviour -- meant the first to finish deleted the
record while the second was still pouring, and later AddBytes calls were then
dropped because AddBytes ignores bytes for a session with no live record. The
stream went invisible to authoritative monitoring while still serving.

Track now returns a Lease that the request-scoped caller releases exactly once;
teardown happens when the last live lease is released. A plain refcount would
have been wrong: Track(A) -> Remove -> Track(B) -> Release(A) decrements B, and
clamping at zero does not help because the count legitimately belongs to B. That
is not hypothetical -- the transcode node deliberately replaces sessions under
the same id so a quality switch does not orphan ffmpeg, and it calls
unconditional Remove from its reaper and stop paths. So each generation carries
an epoch, Remove and Cleanup bump it, and a release from a superseded generation
is a logged no-op. Lease identity is a set rather than a counter, which makes a
duplicate release detectable instead of silently destructive.

The transcode node keeps using Remove: its Track calls are not request-scoped and
are correctly owned by session lifecycle. "Every Track needs a paired Release" is
true only of the request-scoped callers.

#8 -- async transcode tracking could leave a permanent ghost. The tracking write
ran as a bare goroutine with a WithoutCancel context, so if stop won the race the
delayed Track recreated the record after cleanup -- and because it landed in
sessions, Snapshot treated it as live until Remove and it NEVER idle-expired. A
permanent phantom inflating its owner's count, able to trigger false over-cap
kills of that user's real streams. The write now takes the per-session lifecycle
lock that stop and reap already hold, and re-checks session pointer identity
before writing, so a stopped or replaced generation cannot resurrect a record.
Pointer identity rather than id equality is what makes same-id replacement safe.
The write stays off the request path -- the API server and the playback client
are blocked on the 202.

#9 + M3 -- protocol-v3 counted one stream twice. The stream token carries a
transport id distinct from the logical session id, and the node tracked under the
transport id while the API/proxy record used the logical one, so mergeStreams saw
two streams. M3 was the reason this had not yet bitten: the v3 fresh-start caller
sent no owner attribution at all, so the transport record landed under user 0,
which the enforcer skips -- silently exempting the stream from the cap entirely.
Fresh v3 starts now carry the logical session id and full owner attribution
(both were already in scope at the call site), and merging is keyed on logical
identity where present via one shared helper used by both merge functions, which
had already drifted apart once.

The enforcer view resolves SessionID to the logical id so a kill targets the real
session rather than a replaceable transport generation. The raw admin view keeps
the transport id and exposes logical_session_id as an additive omitempty field,
advertised on the node-sessions capability endpoint, so the v1 response shape is
unchanged.

GAP-15 -- edge transcode liveness was request-observed. touchTranscodeSession
fired before proxying, so hammering dead segment URLs advanced LastServedAt with
zero bytes served. Visibility and liveness are now separate operations:
EnsureEphemeral makes a session visible without claiming bytes were served, and
served-byte liveness advances only from a 2xx/206 upstream response. Previously
the proxy metered every upstream body regardless of status, so a node 404's error
body counted as served bytes -- moving the touch later would not have fixed it.

S4 -- LiveLocalSessions moved from the HTTP handlers package to streammonitor,
which owns monitoring. A background enforcer importing api/handlers was
backwards. Pure move; its existing mapping assertions moved with it. The
LastActivityAt fallback inside it is left as-is -- decision A5 removes it in the
liveness batch.

Verified with go test -race across nodesessions, proxy and transcodenode; the
overlap regression test was confirmed to fail under the old unconditional
teardown.

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.

2 participants