Skip to content

fix(catalog): sort TV series by when their episodes were last watched - #5073

Merged
Quick104 merged 5 commits into
Silo-Server:mainfrom
Rhainland:fix/4638-series-date-viewed-sort
Nov 22, 2026
Merged

Quick104 merged 5 commits into
Silo-Server:mainfrom
Rhainland:fix/4638-series-date-viewed-sort

Conversation

@Rhainland

@Rhainland Rhainland commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #4638
Related issue: N/A
Validation tasks: changes #1252 C1 (library sort; not yet passed)

Other clients: Apple N/A (sends the server's date_viewed sort, so this fix applies); Android N/A (same; the missing Date Viewed option on Android TV that the issue mentions is a separate client question); Roku N/A (no Date Viewed sort)

Sorting a TV library's series by Date Viewed did nothing. Ascending and descending both showed the series in title order, and no series card showed a viewed date. Watch history is recorded against episodes, but the sort looked for plays of the series itself, so every series counted as never watched. Series now sort by the most recent time any of their episodes was finished, and each card shows that date. Never-watched series still come last in both directions.

Approach

The Date Viewed sort now counts a finished episode play for its series too, the same way the last_watched filter rule already does. An episode removed from history no longer dates its series. The card's sort_metrics.viewed_at takes the latest finished play of the series' episodes. The Postgres user store works that out in one grouped query per page (SeriesLatestViewedAt on the existing series rollup capability), so no episode lists are loaded into the server. Episodes without a library file still count, as they do in the sort.

In the sort, the two per-item joins stay as they are on main. A third join, added only when the scope can hold a series, dates each series by grouping its episodes' visible finished plays on episodes.series_id. A movie library sorted by Date Viewed runs the same SQL as before. The maintainer review changed the sort to this shape (3ced56f, ae73d76, f195d00). An earlier shape grouped on a key built from item and series IDs together, which PostgreSQL has no statistics for, and it took over a second per page for a profile with a long watch history.

The Plays sort has the same gap for series. It is left for a separate change. Jellyfin-compatible clients are unaffected: SortBy=DatePlayed maps to date added there and does not use this sort.

Validation

  • Go: build, gofmt, go mod tidy -diff and go vet are clean. make lint-changed and make lint-router-recovery report 0 issues.
  • Tests: the catalog, handlers and userstore packages pass against a migrated Postgres. Two new database contracts (added to db-contracts.txt) cover the sort order and the series rollup, including hidden history and hidden progress. A handler test covers the card date.
  • Full make test-go: plugin host, plugin and marker tests fail in this sandbox because it cannot run plugin processes, and they fail the same way on main. TestScanKeepsFileRowAcrossRenameDB failed once in the parallel run and passes on its own, on both this branch and main.
  • Contracts: verify-apiv2-openapi, verify-apiv2-contract, verify-route-inventory, verify-local-paths, verify-case-collisions, verify-size-ratchet and verify-bidi pass. Web code is unchanged.
  • Maintainer review at f195d00:
    • Both new catalog and handler tests fail on main for the reported reason.
    • On a sandbox built from this head, series sort correctly in both directions with the right card dates. Unscoped and movie-scoped requests work, and removing an episode from history removes its series' date.
    • A 60-card TV page for a profile with 50k finished plays takes about 95 to 190 ms, against about 1.2 s at 68d23d0.
  • Local build: a TV library with three synthetic series. Bravo's first episode was marked watched, then Alpha's five seconds later, and Charlie was not watched. The steps were run on main and then on this branch, with the same data.

Evidence

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

Surface and build: web library page, TV library, Library tab, sorted by Date Viewed, at 1440px and 390px; local builds of main and this branch.

API excerpts from the same steps (GET /api/v2/catalog?library_id=…&type=series&sort=…):

main, sort=date_viewed and sort=-date_viewed (identical):
Alpha Show    sort_metrics.viewed_at=null
Bravo Show    sort_metrics.viewed_at=null
Charlie Show  sort_metrics.viewed_at=null

this branch, sort=date_viewed:
Bravo Show    sort_metrics.viewed_at=2026-11-21T17:51:41Z
Alpha Show    sort_metrics.viewed_at=2026-11-21T17:51:46Z
Charlie Show  sort_metrics.viewed_at=null

this branch, sort=-date_viewed:
Alpha Show    sort_metrics.viewed_at=2026-11-21T17:51:46Z
Bravo Show    sort_metrics.viewed_at=2026-11-21T17:51:41Z
Charlie Show  sort_metrics.viewed_at=null

this branch, after removing Alpha's episode from history:
Bravo Show    sort_metrics.viewed_at=2026-11-21T17:51:41Z
Alpha Show    sort_metrics.viewed_at=null
Charlie Show  sort_metrics.viewed_at=null

Sorting episodes by Date Viewed, and series by title, give the same results as before.

Risks

The Date Viewed sort now joins episodes once per finished play, as the last_watched rule already does. Only this sort is affected. On the History page, a series card now shows the date of its latest finished episode. That page orders by the latest history event, including unfinished ones, so a series whose newest event is unfinished can show an earlier date than its position suggests. Movie cards there already behave this way.

Checklist

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

Council review

Rounds: 4, last reviewed f195d00

Member Round 1 Round 2 Round 3 Round 4
Sol (gpt-6.2-sol, xhigh) 7/10 6.5/10 unavailable (head moved) 8/10
Opus (claude-opus-5-5, high) 7.5/10 8/10 8/10 8.5/10
Gemini (gemini-4-neon, xhigh) 7/10 unavailable (head moved) unavailable (head moved) 8.5/10

Fixed: a movie library paid for the series join; a failed series rollup was dropped silently; the TV page took over a second for a long watch history (nested-loop plans, twice). Answered: the generic-plan risk on the rollup didn't reproduce. Repeat-play dates, the Plays sort, Jellyfin DatePlayed and the History page date are follow-ups that predate this PR.

AI Disclosure

  • Harness: Claude Code (via T3 Code); Codex CLI for code review
  • Tool(s): Claude Code, Codex CLI, Playwright (headless Chromium)
  • Model(s): claude-opus-5-5; gpt-6.2-sol (code review)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: two independent reviews of the full diff (Codex and a separate Claude subagent), covering correctness, repository standards and the issue's request. Fixed: the series card date fetched every finished play with offset paging, so it now uses one grouped query per page, which also avoids failing on a play with no duration. A failed episode lookup no longer blanks every card's date. Other changes: reused the existing series-ID helper and renamed the new field so its "all episodes" meaning is clear. After bot review, the card date moved from per-episode reads in Go to one SQL rollup; a second dual review (Codex gpt-6.2-sol and Claude Opus 5.5) of that commit found no correctness or spec problems, and its three low notes (reuse the shared progress visibility rule, test hidden progress, let the planner choose the join) were applied. Not changed: the History page date mismatch noted under Risks, which movie cards already show, and the two subqueries the sort already duplicated. The maintainer review's council is in Council review above.
  • Maintainer review commits (3ced56f, ae73d76, f195d00): Claude Code, claude-opus-5-5.

Note

Sort TV series by last-viewed episode in date_viewed catalog sorting

  • Previously, a series had no date-viewed metric unless the series item itself had a history or progress entry. Now its latest episode play is used to date it.
  • Adds SeriesLatestViewedAt to the SeriesEpisodeRollupStore interface and implements it in PostgresUserStore in progress.go. It returns each series' latest completed, visible episode timestamp from history or progress rows.
  • The API handler uses this rollup via the new listViewedAtSortMetrics helper in items.go, taking the latest timestamp across history, progress, ebook progress, and series rollup. The query builder adds a matching sort join in query_builder.go.
  • Behavioral Change: series without any qualifying episode play get no date-viewed metric and sort last in date_viewed order. Rollup store implementations of SeriesEpisodeRollupStore must add SeriesLatestViewedAt; unsupported stores are skipped.

Macroscope summarized f195d00.

… sort

Watch history is recorded against episodes, so sorting a TV library by
Date Viewed found no date for any series and both directions fell back
to title order. The sort now rolls each finished episode play up to its
series, as the last_watched rule already does, and a series card shows
the date of its latest finished episode.
@silo-triage silo-triage Bot added the size/L 200–499 added + deleted lines (all files); change volume, not priority. label Nov 21, 2026
@silo-kody

silo-kody Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

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

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

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code impact: polish Annoyance, cosmetic, or nice-to-have priority: P2 Limited scope, workaround exists, or polish labels Nov 21, 2026
@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Series date-viewed sorting now includes completed episode activity in catalog results and API metrics. The Postgres user store provides each requested series’ latest visible completed history or progress timestamp.

Changes: Series Date-Viewed Sorting

Layer / File(s) Summary
Series timestamp contract and query
internal/userstore/progress_helpers.go, internal/userstore/pgstore/progress.go, internal/userstore/pgstore/progress_test.go, internal/jellycompat/content_direct_test.go, scripts/ci/db-contracts.txt
The store contract and Postgres implementation return the latest visible completed history or progress timestamp for each requested series. Tests cover the query and stores that implement the contract.
Catalog series sorting
internal/catalog/query_builder.go, internal/catalog/search_personalized_sort_db_test.go, scripts/ci/db-contracts.txt
The catalog query adds completed episode history and progress timestamps to series date-viewed sorting. A database test checks ascending and descending order.
API date-viewed metrics
internal/api/handlers/items.go, internal/api/handlers/items_sort_metrics_test.go
The API separates date-viewed metrics from play counts and includes available series rollup timestamps. Tests cover a series with episode activity and an unseen series.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: quick104, blurbery

Merge Risk: Minimal · up to f195d

Series Date Viewed sorting and card dates now reflect when a series' episodes were last watched, and never-watched series sort last in both directions. The change adds a query to an existing sort path and a new method on a store interface. No concrete defect was found, and database-backed tests cover the new behavior.

Security architecture risk: Minimal · up to f195d

The inspected change preserves account and profile isolation and excludes hidden episode activity before calculating series timestamps. It introduces no identified security regression or new persistent state requiring rollback coordination.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The added output exposes a derived latest-viewed timestamp and corresponding ordering for series, not individual history entries. The inspected SQL confines contributing activity to one account and profile; the API additionally confines results to series in its item list.

Trust Boundaries and Controls

  • observed — The potential hidden-history disclosure through a series maximum is controlled in both implementations: history at or before hidden_before is excluded using watched_at, and progress at or before that cutoff is excluded using updated_at. Account, profile, and completion predicates apply before aggregation.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: TV series sorting now uses when their episodes were last watched. This matches the raw summary, which adds episode-play attribution to series for the date_viewed sort,…
Linked Issues check Passed Issue #4638 requires TV series in a library to sort by Date Viewed. The Web UI toggle had no effect, and series did not show a viewed date. The reviewed whole-PR summary (merge base 02a9d1d to head f1…
Out of Scope Changes check Passed Each changed area supports the series Date Viewed sort:
- query_builder.go, items.go, and the userstore rollup method with its Postgres implementation form the core change.
- progress_helpers.go adds …
Description check Passed The description is specific and related to the changeset. It explains that Date Viewed sorting of TV series ignored episode watch history, and that the fix dates each series by its latest finished epi…
Full details: Title check

Explanation

The title names the main change: TV series sorting now uses when their episodes were last watched. This matches the raw summary, which adds episode-play attribution to series for the date_viewed sort, and the PR objectives, which describe the same goal. The title is specific and concise, so it passes.

Full details: Linked Issues check

Explanation

Issue #4638 requires TV series in a library to sort by Date Viewed. The Web UI toggle had no effect, and series did not show a viewed date. The reviewed whole-PR summary (merge base 02a9d1d to head f195d00) shows these changes for that requirement:

  • internal/catalog/query_builder.go: dateViewedSortPlan adds a series-level join when the media scope can contain series. It rolls up visible completed history and completed progress rows across episodes, grouped by episodes.series_id. The sort key uses that series timestamp. Other scopes keep the existing expression.
  • internal/userstore/pgstore/progress.go: PostgresUserStore.SeriesLatestViewedAt returns each series' latest visible completed timestamp in one grouped query. It excludes history hidden by watermarks and hidden progress.
  • internal/userstore/progress_helpers.go: SeriesEpisodeRollupStore declares SeriesLatestViewedAt.
  • internal/api/handlers/items.go: listUserSortMetrics sets sort_metrics.viewed_at on series cards from the rollup. A failed rollup leaves series undated. Series without a timestamp sort last.
    Tests: TestCatalogQuerySortsSeriesByEpisodeDateViewedDB (listed in scripts/ci/db-contracts.txt), TestPostgresSeriesLatestViewedAtDB (listed in db-contracts.txt), and TestListSortMetricsDatesSeriesByEpisodeViews. The Android TV Date Viewed option question in the issue is a client UI question, not a server coding requirement for this PR. The PR states that the server sort is the source for Apple and Android clients. The summary does not itemize changes since the previous reviewed head, so this verdict rests on the whole-PR summary. Local API results in the PR description were not independently verified.
Full details: Out of Scope Changes check

Explanation

Each changed area supports the series Date Viewed sort:

  • query_builder.go, items.go, and the userstore rollup method with its Postgres implementation form the core change.
  • progress_helpers.go adds the interface method. This requires the test double in internal/jellycompat/content_direct_test.go to implement SeriesLatestViewedAt. This is a required consequence.
  • items_sort_metrics_test.go, search_personalized_sort_db_test.go, progress_test.go, and the two db-contracts.txt entries verify the change.
    The Plays sort is unchanged. The PR states that Plays is a separate change. The History page date behavior is a documented consequence and is not a new feature. The PR reports no web or client code changes. The summary does not list every hunk, so this verdict rests on the file-level summary.
Full details: Description check

Explanation

The description is specific and related to the changeset. It explains that Date Viewed sorting of TV series ignored episode watch history, and that the fix dates each series by its latest finished episode play and shows that date on the card. It names the touched areas: the Postgres rollup (SeriesLatestViewedAt), the catalog sort join, and the handler card date. It also gives validation steps, the risks, and the behavior for never-watched series, which all match the raw summary.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ddb18c8e-c336-4e5e-99f8-7196868d45a6
Commits

Reviewing files that changed from the base of the PR and between 3ced56f and f195d00.

Files selected for processing: 2

  • internal/api/handlers/items.go
  • internal/catalog/query_builder.go

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review.

Comment thread internal/api/handlers/items.go Resolved
Comment thread internal/api/handlers/items.go Resolved
Comment thread internal/api/handlers/items.go Resolved

@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

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c280610b-c432-4180-8eba-d1e51c7f1cbf
Commits

Reviewing files that changed from the base of the PR and between 1bbc479 and e8fb637.

Files selected for processing: 6

  • internal/api/handlers/items.go
  • internal/api/handlers/items_sort_metrics_test.go
  • internal/catalog/episode_repo.go
  • internal/catalog/query_builder.go
  • internal/catalog/search_personalized_sort_db_test.go
  • scripts/ci/db-contracts.txt

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

Comment thread internal/api/handlers/items.go Resolved
…ng their episodes

The Date Viewed card date listed every episode of every series on the page
and read their progress and history in Go. The series rollup store now
answers it in one grouped query, starting from the series' episodes like the
watch-count rollups, and the episode ID lookup added for it is gone.
@silo-kody

silo-kody Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

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

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

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Comment thread internal/api/handlers/items.go Resolved
Comment thread internal/userstore/pgstore/progress.go Resolved
…how a series

Crediting an episode's plays to its series joins every finished play of
the profile to episodes and doubles the rows before grouping. A movie
library pays for that on every page although no series can appear in it.
The sort now adds the join only when the scope can hold a series. A
failed series rollup for the card date is now logged instead of dropped
without a trace.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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

🤖 Claude Code (claude-opus-5-5)

Maintainer review of 68d23d0. The fix is correct: both new tests (the catalog sort test and the handler card-date test) fail on main for the reported reason and pass here. I found two problems in the new code, both small, and I'm fixing both in a commit on this branch, so there's no need to change anything yourself. The summary comment that follows covers the rest.

Comment thread internal/catalog/query_builder.go Resolved
Comment thread internal/api/handlers/items.go Resolved
@silo-kody

silo-kody Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

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

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

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

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

🤖 Claude Code (claude-opus-5-5)

Second round, on 3ced56f. A cross-provider reviewer found a much larger cost than the one I measured in the first round. That measurement timed only the subqueries, not the page query that joins them. I've confirmed the problem through the real catalog resolver and I'm fixing it in a commit on this branch, so there's no need to change anything yourself.

Comment thread internal/catalog/query_builder.go Resolved
Grouping each play under both its own ID and its series ID gave the
planner a key it had no statistics for. It expected a few rows and joined
the page by nested loop, and a TV page took over a second for a profile
with 50,000 finished plays. Each item's latest play is now taken first and
then credited to its series through episodes, which brings that page to
about 170 ms with the same order. Progress has one row per item, so its
join no longer groups.

The series card date now keeps the rollup's result only when it succeeds,
in a helper of its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

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

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

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

if len(seriesIDs) == 0 || !ok {
return nil
}
viewed, err := rollup.SeriesLatestViewedAt(ctx, profileID, seriesIDs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Kody Rules high

Series viewed-time lookup uses an unbounded database batch

Large requests can send an unbounded batch to the database. Deduplicate seriesIDs, call rollup.SeriesLatestViewedAt in bounded batches, and merge the returned maps.

Kody rule violation: Batch scoped Go lookups and bound dependency fan-out

Prompt for LLM
File internal/api/handlers/items.go, line 1436:

Series viewed-time lookup uses an unbounded database batch

Deduplicate the series IDs and split them into bounded batches before calling the rollup, then merge the returned maps. Passing the entire caller-supplied slice to one database query leaves the batch size unbounded for large requests.

Kody rule violation: [Batch scoped Go lookups and bound dependency fan\-out](https://kodus.siloserver.org/settings/code-review/1247142351/kody-rules/d2a64d9a-568c-46c2-9fa4-ad93c54ef90e?teamId=ba9922fc-c0ea-4cf8-87bb-9d4f42ffc73e)

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

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.

🤖 Claude Code (claude-opus-5-5)

This is the same point as the earlier thread on SeriesLatestViewedAt. listSeriesViewedAt only moved that call into a helper. seriesItemIDs deduplicates the IDs, and they come from one catalog page, which the browse plan caps (100 by default). That's the same page-scoped list SeriesEpisodeWatchCounts already takes in one ANY($3) query. It runs one grouped query per page, so batching it would add a loop without bounding anything a caller can grow.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

That makes sense. If seriesItemIDs deduplicates the IDs and every caller supplies a bounded catalog page, the lookup is already bounded at the request boundary. On that basis, I’d withdraw the suggestion to deduplicate and batch the call.

I haven’t independently verified the call paths or the maximum page size, so the conclusion depends on those guarantees holding for every caller—not just the default page size being 100.

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

🤖 Claude Code (claude-opus-5-5)

Third round, on ae73d76. One more finding in the sort SQL I added in the previous round. I'm fixing it in a commit on this branch, so there's no need to change anything yourself.

Comment thread internal/catalog/query_builder.go Resolved
The previous shape still ended in a GROUP BY over a UNION ALL, which
PostgreSQL has no statistics for. When the page's row estimate was small,
such as a library not yet analyzed, the planner joined it by nested loop
and the first page took over a second. The two per-item joins are back to
what main runs. A third join, added only when the scope can hold a series,
groups the episodes' visible finished plays on episodes.series_id, as
SeriesLatestViewedAt does, and the sort key takes the latest of the three.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

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

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

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Comment on lines +1791 to +1792
SELECT uwh.media_item_id, uwh.watched_at AS viewed_at
FROM user_watch_history uwh

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Performance medium

Series sorting joins repeated history plays before aggregating them

Repeated plays increase join and aggregation work for frequently replayed episodes. Group user_watch_history by media_item_id and take the maximum visible watched_at before joining to episodes.

Prompt for LLM
File internal/catalog/query_builder.go, lines 1791-1792:

Series sorting joins repeated history plays before aggregating them

The series sort joins every history event to `episodes` before collapsing repeated plays, so frequently replayed episodes produce one join and aggregation input per play instead of one per episode. Group history by `media_item_id` and take the maximum visible `watched_at` before joining to `episodes`, as the previous sort plan did.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

@Quick104

Copy link
Copy Markdown
Contributor

🤖 Claude Code (claude-opus-5-5)

Maintainer review summary

Reviewed head: f195d00. The review started at 68d23d0 and pushed three commits to this branch.

Fit: 9/10 · Readiness: 9/10 — ready (assuming CI is green)

Fit. This fixes a broken sort in core library browsing, and every first-party client already sends it. It reuses the series-credit rule that the last_watched filter already applies. It adds no setting or API surface; the only addition is an internal store method.

Readiness. The PR's catalog and handler tests fail on main for the reported reason, which is title order and no series date. A fresh sandbox built from f195d00 showed the fix live, and the query cost of a heavy profile is back to a reasonable level.

What the review changed

  • Movie and other non-series scopes skip the series work (3ced56f). The Date Viewed sort now credits episodes to their series only when the scope can hold a series. Before this, a movie library paid for joining every finished play to episodes.
  • A failed series rollup is logged (3ced56f, ae73d76). The card falls back to no date, and the rollup's result is kept only when it succeeds.
  • The TV page is no longer slow for a long watch history (ae73d76, then f195d00). Grouping on a key built from both item and series IDs left PostgreSQL with no statistics. It then joined the page by nested loop, which took about 1.2 s for a 60-card page on a profile with 50k finished plays. On a small library with stale statistics, a later version still took over a second on its first page. The final shape keeps main's two per-item joins unchanged. Only when the scope can hold a series, it adds one join that groups episode plays on episodes.series_id, the same way SeriesLatestViewedAt does. On the same fixture, the page takes about 95 to 190 ms and returns the same rows in the same order. main takes about 70 to 85 ms but returns the wrong order.

Verification

  • Tests that fail on main: TestCatalogQuerySortsSeriesByEpisodeDateViewedDB and TestListSortMetricsDatesSeriesByEpisodeViews. TestPostgresSeriesLatestViewedAtDB covers the new rollup method only.
  • Packages: catalog, handlers, userstore and jellycompat pass against a migrated Postgres. make lint-changed is clean.
  • Live, on a sandbox built from f195d00: two series sort correctly in both directions with the right card dates, and unwatched series come last. An unscoped request gives the same order. A movie library sorted by Date Viewed works. Removing an episode from history removes its series' date.
  • Evidence: https://evidence.siloserver.org/r/silo-server/pr-5073-review/

Council review

Member Round 1 (68d23d0) Round 2 (3ced56f) Round 3 (ae73d76) Final (f195d00)
Sol (gpt-6.2-sol, xhigh) 7/10 6.5/10 cancelled, head moved 8/10
Opus (claude-opus-5-5, high) 7.5/10 8/10 8/10 8.5/10
Gemini (gemini-4-neon, xhigh) 7/10 cancelled, head moved cancelled, head moved 8.5/10

Left for the maintainers, none blocking

  • Repeat plays: the Date Viewed rule, here as on main for movies and episodes, counts a completed progress row's updated_at as a finish time. Rewatching an episode without finishing it moves that row's date, so it now moves its series too.
  • Plays sort: the Plays sort has the same series gap, as the PR description says.
  • Jellyfin: SortBy=DatePlayed and series LastPlayedDate don't use the new rollup.
  • History page: History orders by recorded events, so a card's finished-play date can disagree with its position.
  • Shared rule: user_last_watched and this sort compute the same rule separately. Merging them didn't pay off: the CTE was slower and would add ebook completions to the sort.
  • Test coverage: no committed test pins the scope gate or the plan shape. A test that asserted on timing or plan shape would be fragile.
  • Other edge cases:
    • A browse cursor issued before an upgrade can end that browse early, once.
    • A history read failure also drops series and progress dates, as on main.
    • A library with no statistics yet can take a few hundred ms on its first pages until it's analyzed.
    • The unused rollupCapableStore test fake in notifications no longer satisfies the interface.

Checks

  • Validated features: not run. This account can't read the validation board, so the PR body's changes #1252 C1 line is unconfirmed.
  • User manual: unaffected. The public docs don't describe the Date Viewed sort.
  • Apple/Android parity: this is a server-only change. The clients send date_viewed already and benefit as is.

@Quick104
Quick104 merged commit b1d07ad into Silo-Server:main Nov 22, 2026
23 of 25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code impact: polish Annoyance, cosmetic, or nice-to-have priority: P2 Limited scope, workaround exists, or polish size/L 200–499 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] TV Series sorting by date viewed not working

2 participants