Skip to content

feat(catalog): Latest Episodes sort — order series by newest episode file - #283

Merged
Quick104 merged 4 commits into
Silo-Server:mainfrom
fluxis:feat/latest-episodes-sort
Jul 5, 2026
Merged

Quick104 merged 4 commits into
Silo-Server:mainfrom
fluxis:feat/latest-episodes-sort

Conversation

@fluxis

@fluxis fluxis commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Problem

Every recently-added surface reflects when a SERIES was first added — linking a new episode file never bumps the series' media_item_libraries.first_seen_at (ON CONFLICT DO NOTHING), so a long-running show with a fresh episode sorts as stale. Users can't see which shows received new episodes (#202).

Approach

New denorm media_items.latest_episode_added_at (migration + backfill + partial series index), mirroring the last_air_date_at precedent. Source of truth is episode_libraries.first_seen_at; all three insert paths (UpdateEpisodeLink, BulkLinkEpisodesBySeries, scanner folder restore) bump the parent series in the same SQL statement — monotonic via GREATEST, and only for genuinely new links (conflict no-ops return no rows). Like last_air_date_at, the value is global rather than access-scoped — same accepted trade-off for an O(1) sort key.

Sort registration in both frameworks: a querySortDefs entry (sections, smart collections, and /v1/catalog accept it automatically via QuerySortFieldSet) and a buildOrderByPlan case for the browse path. NULLS LAST so movies and episode-less series trail.

Jellyfin compat: SortBy=DateLastContentAdded — Jellyfin's standard sort behind the TV "Latest" shelf, which clients already send — now maps to the new sort instead of silently collapsing to series creation date. Existing Jellyfin/compat clients get correct behavior with no client changes. DatePlayed keeps its previous created_at mapping instead of piggybacking on the same case.

Web picker: "Latest Episode Added" (series scope), sibling of "Latest Episode Air Date".

API contract

Additive-only per the v1 rules: a new accepted sort value; both frameworks already fall back gracefully on unknown values, so older servers/clients interop unchanged. The compat remap is a behavior change existing clients will feel — deliberately, since the previous mapping was wrong.

Testing

  • DB-backed test covering both link paths: first link stamps, newer link bumps, conflict re-link does not re-bump.
  • Sort-plan tests for both frameworks (denorm column read, no joins/args, NULLS LAST).
  • mapSortBy tests pinning the new mapping and the DatePlayed split.
  • Live-validated on a production deployment (19,048/19,140 series backfilled in seconds): Jellyfin /Items?SortBy=DateLastContentAdded order matched the SQL denorm order exactly, tracking an in-flight library re-ingest in real time; series that received new episodes today surfaced above newly-added series.

Follow-ups (out of scope)

  • Optional built-in "Latest Episodes" home-row recipe (the sort is already usable in custom sections/collections).
  • silo-android / silo-apple can expose the new sort in native pickers; they already benefit via the Jellyfin mapping.

Fixes #202

AI-use disclosure

Implemented with Claude Code (test-first, live-validated); human-reviewed before submission.

🤖 Generated with Claude Code

fluxis and others added 2 commits July 2, 2026 20:47
…file

Adds a latest_episode_added sort so users can see which shows received
new episodes. Today's recently-added surfaces reflect when the SERIES
was first added: linking a new episode file never bumps the series'
media_item_libraries.first_seen_at (ON CONFLICT DO NOTHING), so a
long-running show with a fresh episode sorts as stale (Silo-Server#202).

- New denorm media_items.latest_episode_added_at (migration + backfill
  + partial series index), mirroring the last_air_date_at precedent.
  Source of truth is episode_libraries.first_seen_at; the three insert
  paths (UpdateEpisodeLink, BulkLinkEpisodesBySeries, scanner folder
  restore) bump the parent series atomically in the same statement,
  monotonically via GREATEST, and only for genuinely new links.
- Sort registered in both frameworks: querySortDefs (sections + smart
  collections + /v1/catalog pick it up automatically via
  QuerySortFieldSet) and the browse buildOrderByPlan path.
- Jellyfin compat: SortBy=DateLastContentAdded now maps to the new sort
  instead of silently collapsing to series creation date — Jellyfin
  clients already send this for the TV "Latest" shelf, so they get the
  correct behavior with no client changes. DatePlayed keeps its old
  created_at mapping instead of piggybacking.
- Web sort picker gains "Latest Episode Added" (series scope).

Additive-only per v1 API rules: new sort value, no field/status changes.

Part of Silo-Server#202
Fixes Silo-Server#202

Co-Authored-By: Claude Fable 5 <[email protected]>
The picker-side QuerySortField gained the value but the api-layer
QuerySort union did not, breaking the production tsc build.

Part of Silo-Server#202

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@Quick104, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 55 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 48c3a7f0-8136-4dc7-ad63-4ba41b997492

📥 Commits

Reviewing files that changed from the base of the PR and between 5172155 and 978b5e3.

📒 Files selected for processing (14)
  • internal/catalog/browse.go
  • internal/catalog/episode_added_denorm.go
  • internal/catalog/episode_library_repo.go
  • internal/catalog/query_builder_test.go
  • internal/catalog/query_definition.go
  • internal/jellycompat/query.go
  • internal/jellycompat/query_test.go
  • internal/metadata/service.go
  • internal/scanner/episode_added_denorm_test.go
  • internal/scanner/file_repo.go
  • internal/scanner/scanner.go
  • migrations/sql/20260702183852_media_items_latest_episode_added_denorm.sql
  • web/src/api/types.ts
  • web/src/lib/querySortOptions.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@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: 6acf3529a2

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread internal/scanner/file_repo.go Outdated
Comment on lines +2943 to +2945
bumped AS (
UPDATE media_items mi
SET latest_episode_added_at = GREATEST(COALESCE(mi.latest_episode_added_at, sub.latest_added), sub.latest_added)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Recompute the denorm when episode links are removed

This only ever bumps latest_episode_added_at upward from newly inserted episode_libraries rows, but the same UpdateEpisodeLink statement can delete the previous episode membership below when a file is re-linked to another episode. In that scenario, or when the latest/last episode membership is later removed by reconciliation, the old parent series keeps a non-null/stale timestamp and will continue to sort as recently updated even when its current episode_libraries source of truth no longer has that row.

Useful? React with 👍 / 👎.

Comment on lines +439 to +442
case "datelastcontentadded":
// Jellyfin's standard "Latest" sort for TV libraries: shows ordered
// by their most recently added episode (issue #202).
return "latest_episode_added"

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 Keep DateLastContentAdded scoped to series requests

mapSortBy is used for all Jellyfin /Items browse requests, not just TV libraries, so SortBy=DateLastContentAdded with IncludeItemTypes=Movie now orders by mi.latest_episode_added_at. That column is only populated for series, so movie rows all compare as NULL and fall through to the tiebreaker instead of preserving the previous added-date ordering for movie libraries.

Useful? React with 👍 / 👎.

@Quick104

Quick104 commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Code review

Found 2 issues (both confirm the earlier Codex inline comments — I validated each against the code):

  1. latest_episode_added_at is only ever bumped upward (GREATEST) but is never recomputed when episode_libraries rows are removed. The same UpdateEpisodeLink statement deletes the old episode's membership when a file is re-linked, so a series whose newest membership was just removed keeps a stale timestamp and continues sorting as recently updated. The sibling last_air_date_at denorm this PR cites as precedent uses a full MAX() recompute with IS DISTINCT FROM precisely so decreases are handled; the same pattern is needed here (and on other membership-removal paths).

-- Bump the parent series' latest-episode-added denorm for genuinely
-- new links only (conflict no-ops return no rows). Powers the
-- "Latest Episodes" sort (issue #202).
bumped AS (
UPDATE media_items mi
SET latest_episode_added_at = GREATEST(COALESCE(mi.latest_episode_added_at, sub.latest_added), sub.latest_added)
FROM (
SELECT e.series_id, MAX(i.first_seen_at) AS latest_added
FROM inserted i
JOIN episodes e ON e.content_id = i.episode_id
GROUP BY e.series_id
) sub
WHERE mi.content_id = sub.series_id
AND mi.type = 'series'
)
DELETE FROM episode_libraries el
USING previous p
WHERE p.old_episode_id IS NOT NULL
AND p.old_episode_id <> $1
AND el.media_folder_id = p.media_folder_id
AND el.episode_id = p.old_episode_id
AND NOT EXISTS (
SELECT 1
FROM media_files mf
WHERE mf.media_folder_id = el.media_folder_id
AND mf.episode_id = el.episode_id
AND mf.missing_since IS NULL
)

  1. mapSortBy is used for all jellycompat /Items requests, not just series browses, so SortBy=DateLastContentAdded with IncludeItemTypes=Movie now sorts by mi.latest_episode_added_at, which is NULL for every movie — movie libraries lose the previous created_at ordering and fall through to the tiebreaker. The remap needs to be scoped to series requests.

return "created_at"
case "datelastcontentadded":
// Jellyfin's standard "Latest" sort for TV libraries: shows ordered
// by their most recently added episode (issue #202).
return "latest_episode_added"
default:
return "created_at"

I am pushing fixes for both to this branch.

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

Quick104 and others added 2 commits July 2, 2026 21:32
…ips are removed

The denorm was only ever bumped upward (GREATEST) at insert time, but
UpdateEpisodeLink also deletes the old episode's library membership on
re-link, and reconciliation/path-prefix clears remove memberships too —
leaving a stale timestamp that kept the series sorting as recently
updated. All removal paths now run in a transaction and finish with a
shared full MAX() recompute (catalog.RecomputeSeriesLatestEpisodeAdded)
that also resets to NULL when no memberships remain, mirroring the
last_air_date_at maintenance pattern.

Sequential statements are load-bearing here: data-modifying CTEs are
invisible to reads in the same statement, which also silently no-op'd
the old path-prefix membership delete.

Co-Authored-By: Claude Fable 5 <[email protected]>
…uests

mapSortBy runs for every /Items browse, so the latest_episode_added
mapping leaked into movie and untyped requests where the column is
always NULL, destroying the previous created_at ordering. The sort now
falls back to created_at unless IncludeItemTypes is exactly Series.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104

Quick104 commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Both issues addressed:

  • ca72674: all episode-membership removal paths (UpdateEpisodeLink re-link, path-prefix clears, folder reconciliation, metadata rebind) now run transactionally and finish with a shared full-MAX recompute (catalog.RecomputeSeriesLatestEpisodeAdded) that lowers or NULLs latest_episode_added_at from the episode_libraries source of truth, mirroring the last_air_date_at maintenance pattern. Splitting into sequential statements also fixes a latent no-op: the old same-statement deleted CTE in the path-prefix clear read the pre-update media_files snapshot, so its NOT EXISTS guard could never pass.
  • 978b5e3: jellycompat DateLastContentAdded maps to latest_episode_added only when IncludeItemTypes is exactly Series; movie and untyped requests keep the previous created_at ordering.

DB-backed regression tests extended (re-link lowers/NULLs the old series, bumps the new one; reconciliation reset). Verified with go build ./..., go vet, and the scanner/catalog/jellycompat suites — the two TestBeginWebOperation* failures are pre-existing on the branch (fail identically without these changes; /proc-dependent). Diff written by GPT-5.5 (Codex) under review supervision; validated and committed by Claude.

@Quick104
Quick104 merged commit f32cb65 into Silo-Server:main Jul 5, 2026
1 check passed
Quick104 added a commit that referenced this pull request Jul 6, 2026
…every call (#321)

The statement ended with SELECT COUNT(*) FROM inserted, but the inserted
CTE has no RETURNING clause — PostgreSQL rejects referencing such a CTE
(SQLSTATE 0A000), so every UpdateEpisodeLink call has errored since #283.
The sole caller logs a warning and continues, so the metadata-side
single-file episode relink silently did nothing: episode_id stayed stale,
episode_libraries rows were not inserted, latest_episode_added_at was not
bumped. Bulk linking uses the correct pattern and masked the breakage.

The INSERT is now the top-level statement; the count was unused.
Verified against a migrated PostgreSQL scratch database:
TestEpisodeLinkMaintainsLatestEpisodeAdded fails on main with the exact
error and passes with this change.

Fixes #320

Co-authored-by: Claude Fable 5 <[email protected]>
Quick104 added a commit that referenced this pull request Jul 10, 2026
…every call (#321)

The statement ended with SELECT COUNT(*) FROM inserted, but the inserted
CTE has no RETURNING clause — PostgreSQL rejects referencing such a CTE
(SQLSTATE 0A000), so every UpdateEpisodeLink call has errored since #283.
The sole caller logs a warning and continues, so the metadata-side
single-file episode relink silently did nothing: episode_id stayed stale,
episode_libraries rows were not inserted, latest_episode_added_at was not
bumped. Bulk linking uses the correct pattern and masked the breakage.

The INSERT is now the top-level statement; the count was unused.
Verified against a migrated PostgreSQL scratch database:
TestEpisodeLinkMaintainsLatestEpisodeAdded fails on main with the exact
error and passes with this change.

Fixes #320

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

* feat(catalog): Latest Episodes sort — order series by newest episode file

Adds a latest_episode_added sort so users can see which shows received
new episodes. Today's recently-added surfaces reflect when the SERIES
was first added: linking a new episode file never bumps the series'
media_item_libraries.first_seen_at (ON CONFLICT DO NOTHING), so a
long-running show with a fresh episode sorts as stale (Silo-Server#202).

- New denorm media_items.latest_episode_added_at (migration + backfill
  + partial series index), mirroring the last_air_date_at precedent.
  Source of truth is episode_libraries.first_seen_at; the three insert
  paths (UpdateEpisodeLink, BulkLinkEpisodesBySeries, scanner folder
  restore) bump the parent series atomically in the same statement,
  monotonically via GREATEST, and only for genuinely new links.
- Sort registered in both frameworks: querySortDefs (sections + smart
  collections + /v1/catalog pick it up automatically via
  QuerySortFieldSet) and the browse buildOrderByPlan path.
- Jellyfin compat: SortBy=DateLastContentAdded now maps to the new sort
  instead of silently collapsing to series creation date — Jellyfin
  clients already send this for the TV "Latest" shelf, so they get the
  correct behavior with no client changes. DatePlayed keeps its old
  created_at mapping instead of piggybacking.
- Web sort picker gains "Latest Episode Added" (series scope).

Additive-only per v1 API rules: new sort value, no field/status changes.

Part of Silo-Server#202
Fixes Silo-Server#202

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(web): include latest_episode_added in the api QuerySort field union

The picker-side QuerySortField gained the value but the api-layer
QuerySort union did not, breaking the production tsc build.

Part of Silo-Server#202

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(scanner): recompute latest_episode_added_at when episode memberships are removed

The denorm was only ever bumped upward (GREATEST) at insert time, but
UpdateEpisodeLink also deletes the old episode's library membership on
re-link, and reconciliation/path-prefix clears remove memberships too —
leaving a stale timestamp that kept the series sorting as recently
updated. All removal paths now run in a transaction and finish with a
shared full MAX() recompute (catalog.RecomputeSeriesLatestEpisodeAdded)
that also resets to NULL when no memberships remain, mirroring the
last_air_date_at maintenance pattern.

Sequential statements are load-bearing here: data-modifying CTEs are
invisible to reads in the same statement, which also silently no-op'd
the old path-prefix membership delete.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(jellycompat): keep DateLastContentAdded scoped to series-only requests

mapSortBy runs for every /Items browse, so the latest_episode_added
mapping leaked into movie and untyped requests where the column is
always NULL, destroying the previous created_at ordering. The sort now
falls back to created_at unless IncludeItemTypes is exactly Series.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Quick <[email protected]>
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.

[v1] 'Latest Episodes' sort/filter for sections and collections

2 participants