Repository navigation
feat(jellycompat): support Autoscan via Jellyfin media-update endpoint - #8
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughAdds 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. ChangesAutoscan Jellyfin Compatibility
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
internal/jellycompat/handlers_autoscan.go (1)
145-145: ⚡ Quick winAvoid returning raw internal errors to clients.
Line 145 exposes the raw
errstring 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.godocs/scan-api.mddocs/superpowers/specs/2026-05-24-jellyfin-autoscan-scan-compat-design.mdinternal/api/handlers/libraries.gointernal/jellycompat/auth_api_key.gointernal/jellycompat/auth_test.gointernal/jellycompat/handlers_autoscan.gointernal/jellycompat/handlers_autoscan_test.gointernal/jellycompat/router.gointernal/jellycompat/server.gointernal/scantrigger/scantrigger.gointernal/scantrigger/scantrigger_test.go
There was a problem hiding this comment.
💡 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".
| for _, req := range requests { | ||
| target, err := r.Resolve(ctx, req) |
There was a problem hiding this comment.
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 👍 / 👎.
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
096d797 to
7d612f6
Compare
There was a problem hiding this comment.
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.godocs/scan-api.mddocs/superpowers/specs/2026-05-24-jellyfin-autoscan-scan-compat-design.mdinternal/api/handlers/libraries.gointernal/jellycompat/auth_api_key.gointernal/jellycompat/auth_test.gointernal/jellycompat/handlers_autoscan.gointernal/jellycompat/handlers_autoscan_test.gointernal/jellycompat/router.gointernal/jellycompat/server.gointernal/scantrigger/scantrigger.gointernal/scantrigger/scantrigger_test.go
| ```json | ||
| { | ||
| "Updates": [ | ||
| { | ||
| "path": "/media/tv/Show/Season 01/Episode.mkv", | ||
| "updateType": "Modified" | ||
| } | ||
| ] | ||
| } |
There was a problem hiding this comment.
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.
| ```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, |
There was a problem hiding this comment.
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.
Reviewed by Cursor Bugbot for commit 09a02a7. Configure here.
| bestLen = rootLen | ||
| } | ||
| } | ||
| return bestRoot, nil |
There was a problem hiding this comment.
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)
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
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
There are 3 total unresolved issues (including 2 from previous reviews).
❌ 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.
| userRepo := auth.NewUserRepository(deps.DB) | ||
| compatDeps.APIKeyValidator = auth.NewAPIKeyRepository(deps.DB) | ||
| compatDeps.APIKeyUserLoader = userRepo | ||
| compatDeps.ScanQueue = deps.LibraryScanQueue |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit eccf68f. Configure here.
|
I was able to add a few fixes to the existing code for it to work and made a commit @Quick104 |
…oscan-scan-compat feat(jellycompat): support Autoscan via Jellyfin media-update endpoint
…compat feat(jellycompat): support Autoscan via Jellyfin media-update endpoint
…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]>
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]>
* 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]>
… 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.


Summary
POST /Library/Media/Updatedroute in jellycompat that resolves changed paths to libraries and enqueues scans via a shared scan trigger resolver (all-or-fail across multi-update requests)GET /Library/VirtualFoldersto return realLocationsfor enabled libraries when called with an admin API key, falling back to the existing items-handler response for normal sessionssa_) on the new Autoscan routes (X-Emby-Token,X-Mediabrowser-Token,Authorization: Bearer,api_key) so Autoscan's stock Jellyfin target can authenticateinternal/scantriggerand reuse it from the existing libraries APIscanqueue.Service.EnqueueScans+Repository.CreateBatchfor transactional batch enqueuedocs/scan-api.mdand add the design spec underdocs/superpowers/specs/Testing
go test ./internal/jellycompat/... ./internal/scantrigger/... ./internal/scanqueue/... ./internal/api/handlers/...make lintsa_token and confirmGET /Library/VirtualFolders+POST /Library/Media/Updatedtrigger scansNote
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/VirtualFoldersreturns real filesystemLocationsfor enabled libraries when authenticated with an adminsa_API key (Jellyfin session tokens still use the existing handler).POST /Library/Media/Updatedaccepts Autoscan’sUpdates[]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/scantriggerand reused byPOST /api/v1/scanand the new compat handler. The scan queue gains transactional batch enqueue (CreateBatch/EnqueueScans).docs/scan-api.mdand 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
Improvements
Documentation
Tests