Skip to content

feat(catalog): group recently added TV by arrival time - #1731

Merged
Quick104 merged 2 commits into
Silo-Server:mainfrom
Rhainland:feat/issue-1588-recent-tv-arrival-grouping
Oct 1, 2026
Merged

Quick104 merged 2 commits into
Silo-Server:mainfrom
Rhainland:feat/issue-1588-recent-tv-arrival-grouping

Conversation

@Rhainland

@Rhainland Rhainland commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #1588
Validation tasks: none

Recently Added TV groups new episodes by the scan run that found them (#561). Sonarr and other arr tools send one webhook per imported episode, and each webhook becomes its own scan run, so every episode ends up in its own group. A backfilled season fills the home row with one card per episode of the same show.

This change groups by arrival time instead. An episode first seen within 2 hours of the show's previous arrival joins that group, so a trickle of imports stays one group even when it spans more than 2 hours. A group with one episode is still an episode card. A larger group is the series card, placed by its newest episode. Webhook imports, polling sources, and library scans all group the same way. Episodes added before scan runs were tracked now group this way too; before, they were always series cards.

This PR does not add the per-library or per-profile grouping setting, or the new response fields, proposed in #1588.

Approach

  • Grouping. A window over each show's availability rows, ordered by first_seen_at, starts a new group after any gap longer than 2 hours. Scan-run provenance is still recorded but no longer read here. In catalog cursors, the group's start time replaces the scan-run ID as the event identity.
  • Home row. Grouping the whole library to fill 20 cards took about 300 ms on a synthetic library of 5,000 shows and 200,000 episodes, both on main and with time grouping alone. The home row now uses ListNewest. It takes the Nth newest arrival as a cutoff and groups the full history of every show with an arrival since then. Any group newer than the cutoff belongs to one of those shows, so the result matches the full query. If that gives too few cards, the cutoff moves back. Past 8,192 arrivals, which usually means right after a bulk import, it falls back to the full query. The query runs with SET LOCAL jit = off, because the planner overestimates its cost enough to trigger JIT, and compiling took longer than running it.
  • total_count. On the home row, total_count is now a lower bound: the cards returned, plus one when more exist. It used to be an exact count of every group. The v2 contract already documents it as "at least the number returned", and web, Apple, and Android only compare it with the item limit or with zero. The catalog view still reports the exact count.

Home row on the synthetic library:

main This PR
Default work_mem ~300 ms ~8 ms
work_mem 32 MB ~228 ms ~8 ms
Profile restricted to a few shows (falls back to the full query) ~275 ms ~285 ms

The catalog view keeps the full query. It runs within about 15% of main: cursor paging is slightly slower, and name-prefix search is faster.

Validation

  • Go build, gofmt, go vet, and make lint-changed: clean.
  • DB-backed tests: pass. They cover time grouping, cursor paging, and a new test that compares ListNewest with the full query across randomized arrival patterns, limits, libraries, and access filters, plus a case where the cutoff falls inside a group. Sections tests also pass.
  • make test-db-pins: 25 of 25 pass.
  • verify-apiv2-openapi, verify-apiv2-contract, verify-route-inventory, verify-migration-ledger, and verify-local-paths: pass.
  • make test-go: TestAdminResourceCapabilitiesAndScope in internal/apiv2 and the hardware-probe tests in internal/playback fail. They fail the same way on main in this environment. The internal/jellycompat transcode tests failed in the full parallel run and pass when run alone.
  • Web checks: not run. This PR has no web changes.

Risks

  • Clients that show the home row's total_count as a number would now show a smaller one. None of the first-party clients do.
  • Two cases change on purpose. Separate scan runs less than 2 hours apart now merge into one card. A lone episode with no scan-run record is now an episode card instead of a series card.
  • Apple and Android need no changes, because episode and series cards already exist. The Jellyfin /Items/Latest endpoint turns this grouping off and is unaffected.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.

AI Disclosure

  • Harness: Claude Code (in T3 Code); Codex CLI 0.159.2 for independent review
  • Tool(s): Claude Code; Codex CLI
  • Model(s): claude-opus-5-5; gpt-6-astra and gpt-6.1-sol (review)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: Claude and two independent Codex reviews (gpt-6-astra, gpt-6.1-sol) read the complete diff. They checked grouping semantics, whether the bounded home path matches the full query, cursor ordering, access and snapshot filtering, the JIT handling, and the total_count change. None found a material issue. The only change was one outdated code comment. A deliberate mutation, grouping only the rows after the cutoff, confirmed that the new cutoff test fails when it should.

Note

Group recently added TV by arrival time instead of scan-run identity

  • Recently-added TV cards now group per-series arrival runs: episodes join the same event when consecutive arrivals are no more than 2 hours apart, chained arrivals stay in one group, and a gap longer than 2 hours starts a new event. Grouping ignores scan-run IDs, and a group's event ID is a formatted UTC start timestamp. See recent_tv.go.
  • catalog.RecentTVRepository.ListNewest answers home-row queries from progressively larger bounded recent-arrival windows and falls back to the full unique-target query when a window cannot answer. fetcher.go now uses it, reporting total_count as page length plus one when more cards exist, instead of an exact count.
  • Shared condition construction, result scanning, and SQL helpers were extracted so all recent-TV query shapes derive the same filters and event grouping. Tests now cover chained arrivals across scan runs and cutoffs, plus bounded newest queries.
  • Behavioral Change: cards previously keyed by first_seen_scan_run_id are now keyed by arrival time, so existing event identities change; home-row total_count for recently added TV is a lower bound, not an exact total (documented in catalog-api.md).

Macroscope summarized ed5c43d.

Recently Added TV grouped new episodes by the scan run that found them.
Sonarr and other arr tools send one webhook per imported episode, and
each becomes its own scan run, so a backfilled season showed up as one
card per episode.

Group a show's arrivals by time instead: an episode first seen within 2
hours of the show's previous arrival joins that group. A one-episode
group is an episode card and a larger group is the series card.

The home row now groups only the full history of shows with a recent
arrival, widening the window until it has enough cards and falling
back to the full query. Its total_count becomes a lower bound.
@kody-ai

kody-ai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the `@kody start-review` command at the root of your PR.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Providing Context (Files & MCPs)

Add these hints in your PR description (or a comment) to unlock deeper checks:

  • Ticket / Acceptance Criteria: `Refs: ABC-123` (Linear/Jira/Asana/ClickUp/Trello) or a direct ticket link.
  • Bugfix Validation: a Sentry/Datadog/Bugsnag event link (or paste the stack trace/error message).
  • Endpoint Risk: mention the route (e.g., `POST /api/payments`) or controller/action name.
  • Attach a repo file as context: use an explicit marker like `@file:docs/guide.mdx#L10-L50` (replace with your real path).
  • API Contract Docs: include `@file:openapi.yaml` or `@file:swagger.json` when changing routes/schemas.
  • Definition of Done / Standards: include `@file:DOD.md` or `@file:CONTRIBUTING.md` if your repo has them.
  • Design System Source of Truth: include `@file:ui/index.ts` (replace with your DS entrypoint path).
  • Feature Flags: include the flag key/name and `@file:flags.ts` / `@file:config.json` (and optionally the PostHog flag name).
  • Edge/CDN Rules: link the Cloudflare rule/zone or describe the intended redirect/header behavior.
  • Attach an MCP tool output: use `@mcp<provider|tool>` (replace with an installed MCP provider + tool, e.g., `@mcp<sentry|events.search>`).
Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Access your configuration settings here.

@coderabbitai

coderabbitai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 34e7d0bb-92e5-4167-82a0-4edfd9281c4e

📥 Commits

Reviewing files that changed from the base of the PR and between aa3f29f and ed5c43d.

📒 Files selected for processing (3)
  • internal/api/handlers/items.go
  • internal/catalog/playable_targets.go
  • internal/jellycompat/handlers_items.go

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


📝 Walkthrough

Walkthrough

Recently Added TV events now group episodes by chained arrival times. The home-row path uses a bounded query with a full-query fallback, and reports total_count from the returned targets and hasMore.

Changes

Recently Added TV arrivals

Layer / File(s) Summary
Arrival event grouping and listing
internal/catalog/recent_tv.go, internal/catalog/recent_tv_db_test.go, internal/catalog/recent_tv_cursor_db_test.go, docs/catalog-api.md, internal/adminjob/direct_scan_run.go, internal/api/handlers/items.go, internal/catalog/playable_targets.go, internal/jellycompat/handlers_items.go
TV events group consecutive episode arrivals within two hours. Single-episode events target the episode; larger events target the series. Event ordering and cursor identity use arrival times. Tests cover grouping and pagination; documentation and comments describe the grouping and home-row counts.
Bounded home-row lookup
internal/catalog/recent_tv.go, internal/sections/fetcher.go, internal/catalog/recent_tv_newest_db_test.go
ListNewest queries bounded arrival windows and falls back to List when needed. The fetcher uses the bounded method and sets total_count from returned targets, plus one when hasMore is true. Tests compare bounded results with full-query results.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Fetcher
  participant ListNewest as RecentTVRepository.ListNewest
  participant List as RecentTVRepository.List
  participant Database
  Fetcher->>ListNewest: Request newest unique targets
  ListNewest->>Database: Query bounded arrival window
  Database-->>ListNewest: Return window results
  alt bounded window needs fallback
    ListNewest->>List: Request unique targets
    List->>Database: Query full recent-TV events
    Database-->>List: Return targets and hasMore
    List-->>ListNewest: Return full-query results
  end
  ListNewest-->>Fetcher: Return targets and hasMore
Loading

Suggested reviewers: quick104

Merge Risk: 🟡 Moderate · up to ed5c4

Some libraries may see slower Recently Added TV catalog pages and fallback home loads, although the usual open-profile home row is reported to be faster. Resolve or accept that tradeoff before merging.

Architecture Summary

Architecture risk: 🔵 Low · up to ed5c4

The change affects 2 systems.

Changed systems: internal, docs

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — internal (service) was modified; 9 changed files map to changed impact.
  • observed — docs (service) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in docs/catalog-api.md: Documents recently added TV grouping by episode arrival: an episode within two hours of the previous arrival joins that group, and chained arrivals may span more than two hours. Groups of one return episode cards; larger groups return series cards ordered by newest arrival, regardless of scan method. The home row’s total_count is a lower bound when it exceeds item_limit; the catalog view reports the exact count.
  • observed — Modified behavior in internal/adminjob/direct_scan_run.go: The comments now describe the legacy NULL provenance path and state that Recently Added groups by arrival time, replacing the claim that these files render as series cards.
  • observed — Modified behavior in internal/catalog/recent_tv.go: Adds the errors and pgx imports used by the new bounded recent-TV query path.
  • observed — Modified behavior in internal/catalog/recent_tv.go: Defines a two-hour arrival gap and documents that consecutive arrivals within that gap form one availability event, with single-episode events targeting the episode and larger events targeting the series.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 68.42% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 19 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: Recently Added TV grouping now uses arrival time.
Description check ✅ Passed The description directly explains the problem, arrival-time grouping behavior, home-row changes, testing, risks, and scope exclusions.
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

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.

@macroscopeapp

macroscopeapp Bot commented Sep 30, 2026

Copy link
Copy Markdown

The cases named in the Validation tasks: line (#1140 C4 and #1142 C1/C3) are all Not run; the corresponding curated-home cases in the Apple and Android tasks are also Not run. No recorded result exists to invalidate or unblock, so please replace the line with:

Validation tasks: none

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

Posted via Macroscope — v1 validation impact

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

Two findings. The performance one is inline and needs your call. The other is below.

Low, comment drift: three comments outside the diff still say Recently Added TV makes one card per scan-run event. They are in internal/catalog/playable_targets.go (PlayableTargetInput.Key), internal/api/handlers/items.go (playableTargetInputForItem), and internal/jellycompat/handlers_items.go (loadLatestViaSections). What they describe still holds: a show can appear on two cards with different anchors, and /Items/Latest opts out of the grouping. But the cause is now arrival events, and the repository treats a comment that disagrees with the code as wrong. I'm fixing this in a commit on this branch, so there's no need to change it yourself.

I also checked these and found no problems:

  • ListNewest against the full query: 25 random seeds with forced timestamp ties, arrivals exactly 2 hours apart, episodes in two folders, missing files, shows with no episodes, and open, half, and single-show allow-lists. Bounded and fallback results matched, including event IDs and play anchors.
  • Full cursor walks for both unique and per-event listings.
  • How web, Apple, and Android use total_count. They only adjust it on Continue Watching and Next Up, or compare it with item_limit or zero.

Review by Claude Code (claude-opus-5-5).

return targets, false, err
}
q.UniqueTargets, q.SkipTotal = true, true
targets, _, hasMore, err := r.List(ctx, q)

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.

Needs your call (medium, performance): on episodes with no scan-run record, the full query is about 2.5× slower than on main.

Episodes first seen before scan-run tracking existed have a NULL first_seen_scan_run_id. On main, all of a show's NULL rows become one event, so those shows are cheap to group. This PR splits the same rows at every gap longer than 2 hours. For a show that gets one episode a week, that means one event per episode. That's the grouping the PR is after, but it costs more, and most existing libraries are largely made of such rows.

I seeded a synthetic library of 5,000 shows and 200,000 episodes and ran both trees against the same database. Each figure is the median of 7 runs:

Query No scan-run IDs: main No scan-run IDs: this PR One scan run per episode: main One scan run per episode: this PR
Home row, open profile 304 ms 23 ms 880 ms 15 ms
Home row, profile allowed 20 shows (falls back here) 318 ms 832 ms 630 ms 749 ms
Catalog view, cursor page 309 ms 872 ms 831 ms 822 ms
Catalog view, name prefix 342 ms 751 ms 305 ms 662 ms

The open home row gets much faster either way. On libraries without scan-run IDs, three paths get about 2.5× slower:

  • the home row for profiles whose visible arrivals are too sparse to fill the 8,192-row window;
  • the first home load after a bulk import;
  • the catalog "View all" page.

The description's "within about 15% of main" and "~275 ms vs ~285 ms" figures match the case where episodes carry scan-run IDs. I also measured name-prefix search as slower in both cases, not faster.

Options:

  1. Accept the cost and correct the performance section of the description so it covers episodes without scan-run IDs.
  2. Keep restricted profiles on the bounded path: have the cutoff probe count only arrivals from shows the caller can see, so the window doesn't hit 8,192 rows and fall back. With an allow-list, the probe could read the allowed shows through episodes(series_id) instead of the folder index.
  3. Serve the catalog view's skip_total cursor pages through the same cutoff approach, and keep the full query for exact totals.

I'm not changing this. It's a tradeoff for you and the maintainers.

Three comments still said Recently Added TV keeps one card per scan-run
event. Cards now come from arrival events, so say that.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@kody-ai

kody-ai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the `@kody start-review` command at the root of your PR.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Providing Context (Files & MCPs)

Add these hints in your PR description (or a comment) to unlock deeper checks:

  • Ticket / Acceptance Criteria: `Refs: ABC-123` (Linear/Jira/Asana/ClickUp/Trello) or a direct ticket link.
  • Bugfix Validation: a Sentry/Datadog/Bugsnag event link (or paste the stack trace/error message).
  • Endpoint Risk: mention the route (e.g., `POST /api/payments`) or controller/action name.
  • Attach a repo file as context: use an explicit marker like `@file:docs/guide.mdx#L10-L50` (replace with your real path).
  • API Contract Docs: include `@file:openapi.yaml` or `@file:swagger.json` when changing routes/schemas.
  • Definition of Done / Standards: include `@file:DOD.md` or `@file:CONTRIBUTING.md` if your repo has them.
  • Design System Source of Truth: include `@file:ui/index.ts` (replace with your DS entrypoint path).
  • Feature Flags: include the flag key/name and `@file:flags.ts` / `@file:config.json` (and optionally the PostHog flag name).
  • Edge/CDN Rules: link the Cloudflare rule/zone or describe the intended redirect/header behavior.
  • Attach an MCP tool output: use `@mcp<provider|tool>` (replace with an installed MCP provider + tool, e.g., `@mcp<sentry|events.search>`).
Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Access your configuration settings here.

@Quick104

Quick104 commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Review summary

Reviewed head: ed5c43d (the PR's aa3f29f plus one comment-only commit from this review).

Addressed

  • Comment drift: three comments outside the diff still described one Recently Added TV card per scan-run event. ed5c43d changes them to say arrival event. It changes no code. The three packages build.

Still open

  • Needs your call, performance (see the inline thread on internal/catalog/recent_tv.go): on episodes with no scan-run record, which covers most of an existing library, the full query runs about 2.5× slower than on main. This affects the catalog "View all" page, profiles that fall back from the bounded home-row path, and the first home load after a bulk import. The open-profile home row gets much faster in every case I measured. The thread lists three options. The PR description's performance figures hold only for episodes that carry scan-run IDs.

Verified

  • The PR's DB-backed RecentTV tests pass on a freshly migrated database.
  • In a 25-seed randomized comparison, ListNewest matched the full query on targets, event IDs, AddedAt, play anchors, and hasMore. The seeds covered timestamp ties, gaps of exactly 2 hours, episodes in two folders, missing files, shows with no episodes, and three access scopes. Full cursor walks matched unpaged listings.
  • How web, Apple, and Android read total_count: none depends on an exact home-row count.
  • Other bot feedback: CodeRabbit and Kody raised nothing actionable. The Macroscope validation check was skipped.

Validated features: unaffected. The passed cases on the v1.0 board cover API keys, admin impersonation, Calendar, person browsing, and user management, and none of them reaches Recently Added TV or the home sections. Validation tasks: none is correct.

Validation status: CI on ed5c43d is pending. All required checks passed on aa3f29f.

Mergeability: 7/10 — conditional. The grouping is correct and well tested, and the open home row gets much faster. Two conditions remain: a decision on the slowdown for episodes without scan-run IDs, with the description updated to match, and green CI on the new head.

Review by Claude Code (claude-opus-5-5).

@Quick104
Quick104 merged commit ce6ab55 into Silo-Server:main Oct 1, 2026
8 of 10 checks passed
Quick104 added a commit that referenced this pull request Oct 1, 2026
Main now holds #1697 as a squash commit, so this carries only this
branch's own changes onto it. It also regenerates the v2 OpenAPI
artifact, web types and contract fixtures, which went stale on main when
#1697 merged after #1710 and #1731.

Co-Authored-By: Claude Opus 5.5 (1M context) <[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.

2 participants