Skip to content

fix(history): clear a show's history card when an episode has no file - #2167

Merged
Quick104 merged 2 commits into
mainfrom
fix/issue-2164-history-remove-unlinked-episodes
Oct 8, 2026
Merged

Quick104 merged 2 commits into
mainfrom
fix/issue-2164-history-remove-unlinked-episodes

Conversation

@Quick104

@Quick104 Quick104 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #2164
Related issue: N/A
Validation tasks: none

After a watch-history import, removing a show from a profile's watch history can leave its card on the History page for good. "Remove Show Watch Data" returns success, but the card comes back after every refresh.

The History page shows a watch of any episode on its series card. Removal only reached episodes that have a file in a library. A history import can record a watch for an episode Silo knows only from metadata, and deleting an episode's file leaves the same state. A watch on such an episode was never hidden, so it kept the card. This affects every client that removes history, since removal runs on the server.

Approach

Removing a show or a season now also hides the episodes without a file that the profile has visible history or resume progress for. Episodes without a file that the profile never watched stay out of the removal. A long-running show can have thousands of metadata-only episodes, and hiding all of them would write a permanent hidden-history row and publish a user-state event for each one. Episodes with a file are handled as before.

The catalog gains EpisodeRepository.PartitionIDsBySeries / PartitionIDsBySeason, which split a show's or season's episodes into those with a file and those without in one query. The handler filters them through the user store's existing history and progress reads, in batches of 1,000 to stay under SQLite's bound-variable limit. The change is in the removal seam shared by v1 POST /history/remove and v2 POST /api/v2/history/remove. The request and response shapes are unchanged.

Validation

  • New Postgres-backed test: it fails on main (the watch of the episode without a file survives) and passes here. It covers show and season removal, season removal at item scope, and episode removal at show scope. It also checks that an unwatched episode without a file gets no hidden row. The test is added to scripts/ci/db-contracts.txt so the database job runs it.
  • Unit test: the filter reads large and overlapping candidate lists once each, in batches of at most 1,000.
  • Focused history tests in internal/api/handlers, internal/apiv2, and internal/catalog: pass.
  • Full runs of internal/api/handlers, internal/apiv2, and internal/jellycompat: four tests fail locally, and the same four fail on unmodified main.
  • make lint-changed: 0 issues.
  • Live check on a local server with the same seeded data on both builds. On main, the removal returned 204 and the show stayed in GET /api/v2/history and on the web History page. On this branch it is gone, and the other show remains.

Evidence

Before-and-after captures of the web History page at desktop and phone width, and the API transcripts, are on the evidence page.

Evidence: https://evidence.siloserver.org/r/silo-server/issue-2164/

Risks

  • Removing a show or season now also deletes resume progress for its watched episodes that have no file. Removal already does this for episodes with a file.
  • This changes behavior on /api/v1 through the shared seam. It is a correctness fix with no wire change.
  • Removal now runs two extra user-store reads, both batched over the series' episodes without a file.
  • The filter reads happen before the removal transaction. An import that commits a watch for a previously unwatched file-less episode in that gap is not removed, and the card stays until the user removes the show again. Closing the gap would mean moving the filter into each user store's removal transaction.
  • File-less episodes the profile hadn't watched get no hidden-history marker. If a later import brings an older watch for one of them, it shows up on the series card again. Episodes with a file keep their marker and stay hidden. Marking every file-less episode would bring back the row and event growth described above.
  • The SQLite user store writes the whole removal list in one statement, as it did before. A selection with more than about 32k IDs already fails there on main. This PR adds only watched file-less episodes to that list.

Follow-ups, not in this PR:

  • Native mark-unwatched and jellycompat mark-unplayed also expand a show to episodes with a file only. They clear the show's watched status correctly, since watched counts use episodes with a file, but can leave the same History card behind.
  • Apple and Android call the same endpoint and need no change. The user manual does not describe per-item history removal, so it needs no change.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code, running in T3 Code
  • Tool(s): Claude Code, GitHub CLI, Go toolchain, Playwright (headless Chromium), Docker (local Postgres and Redis); Codex for the adversarial review
  • Model(s): claude-opus-5-5 (implementation and review), Claude Code's sonnet model alias (two review subagents), gpt-6.1-sol (adversarial review)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: Two rounds with Codex (gpt-6.1-sol) on the diff, plus a three-finder Claude review. The first design hid every episode without a file; reviewers flagged that a long-running show could then write thousands of hidden rows and events, so removal now adds only watched ones. Round two found the SQLite bound-variable limit on large selections, fixed with batching, and the race noted under Risks, accepted and documented.

🤖 Generated with Claude Code

Note

Fix history removal to include watched file-less episodes

  • When removing a show, season, or episode from history, watched episodes without a library file are now included in the removal set, so a show's history card clears correctly
  • resolveHistoryRemovalMediaItemIDs returns file-less episode candidates separately from directly removable IDs; seriesEpisodeIDs and seasonEpisodeIDs use new PartitionIDsBySeries/PartitionIDsBySeason repository methods to split episode IDs in one query
  • File-less candidates are removed only if the profile has history or progress for them; reads are deduplicated via compactHistoryItemIDs and batched at 1,000 IDs in watchedHistoryItemIDs
  • Adds a Postgres integration test covering show, season, item, and episode-by-show removal targets, plus a unit test for batching and dedup, registered in db-contracts.txt
  • Behavioral Change: unwatched file-less episodes are now excluded from history removal, whereas previously all resolved episode IDs were treated as removable

Macroscope summarized c562f0d.

The history page shows a watch of any episode on its series card, but
removing the show, a season, or an episode with show scope only hid
episodes that have a library file. A history import can record a watch
for an episode the catalog knows only from metadata, and a deleted file
leaves the same state, so the series card could never be cleared.

Series and season removal now also hide the file-less episodes the
profile has visible history or progress for. Unwatched file-less
episodes stay out of the removal, so a long-running show with few files
does not write thousands of hidden rows or events. The filter reads run
in batches of 1,000 to stay under SQLite's bound-variable limit.

Closes #2164

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

silo-kody Bot commented Oct 8, 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 ❌

@coderabbitai

coderabbitai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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: fadf345e-ef35-49bd-977f-038cccc902fc
📥 Commits

Reviewing files that changed from the base of the PR and between 4c3bd10 and bed3ffe.

📒 Files selected for processing (4)
  • internal/api/handlers/favorites.go
  • internal/api/handlers/favorites_history_remove_test.go
  • internal/catalog/episode_repo.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; 0 remain after this review.


📝 Walkthrough

Walkthrough

History removal now includes file-less episodes when resolving show and season targets. It hides those episodes only when the profile has history or progress for them. The change adds repository queries and tests for target removal and batched lookups.

Changes

Show and season history removal

Layer / File(s) Summary
Resolve file-less episode targets
internal/catalog/episode_repo.go, internal/api/handlers/favorites.go
The repository lists file-less episode IDs by series or season. Target resolution returns file-backed and file-less IDs separately.
Filter and remove watched file-less episodes
internal/api/handlers/favorites.go, internal/api/handlers/favorites_history_remove_test.go, scripts/ci/db-contracts.txt
Removal checks file-less IDs against profile history and progress in batches of 1,000. Tests cover show, season, and episode removal, along with batching and deduplication. The database contract test list includes the new PostgreSQL test.

Priority: ➖ Normal

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

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: rhainland

Merge Risk: 🔵 Low · up to bed3f

A concurrently imported watch may leave a show card visible until removal is repeated. This bounded, known race warrants owner awareness but does not otherwise block merging.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 3 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Issue #2164 requires history removal to hide watched file-less episodes that keep a series card visible. The shared resolver adds file-less episode candidates for show and season targets, then keeps o…
Out of Scope Changes check ✅ Passed The repository queries, handler changes, batching, and tests support issue #2164. The PR description reports no request or response changes, and the diff shows the change in the shared history-removal…
Title check ✅ Passed The title clearly and concisely describes the primary fix: clearing a show's history card when an episode has no file.
Description check ✅ Passed The description is directly related to the changes. It explains the problem, implementation, validation, risks, and affected history-removal paths.
Full details: Docstring Coverage

Explanation

Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 3 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Comment on lines +750 to +754
watchedFileless, err := watchedHistoryItemIDs(ctx, store, profileID, filelessIDs)
if err != nil {
return apiError(http.StatusInternalServerError, "internal_error", "Failed to remove history")
}
addMediaItems(watchedFileless)

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 Bug high

Race condition in file-less candidate filtering omits an episode when its imported watch commits after watchedHistoryItemIDs reads it but before RemoveHistoryItems runs, causing removal to return success without hiding the watch or creating its suppression watermark. Because RemoveHistoryItems alone acquires the profile lock, select watched candidates and remove them under the same profile-scoped transaction lock used by AddHistoryIfMissing.

Prompt for LLM

File internal/api/handlers/favorites.go:

Line 750 to 754:

Race condition in file-less candidate filtering omits an episode when its imported watch commits after watchedHistoryItemIDs reads it but before RemoveHistoryItems runs, causing removal to return success without hiding the watch or creating its suppression watermark. Because RemoveHistoryItems alone acquires the profile lock, select watched candidates and remove them under the same profile-scoped transaction lock used by AddHistoryIfMissing.

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 Author

Choose a reason for hiding this comment

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

The gap is real. It's already listed under Risks as accepted, and I'm leaving it open for a maintainer to decide.

What it takes: an import has to commit a watch for an episode that has no file and had no watch until then, in the few milliseconds between the reads in watchedHistoryItemIDs and the transaction in RemoveHistoryItems. The removal still succeeds for everything else. The new watch is visible, so the series card stays until the user removes the show again, and that second removal hides it. No data is lost.

The fix suggested here moves the candidate check inside the removal transaction under lockImportedHistory. That needs a new UserStore method implemented in both the Postgres and SQLite stores, plus the notifications wrapper, which is more than this bug fix should carry. If a maintainer wants it, I'll do it as a follow-up.

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’s a reasonable scope boundary. The race is a real correctness issue, but you’ve documented the concurrent-import scenario, its impact, and the retry workaround. It doesn’t invalidate the fix for existing file-less watches.

I’d treat this suggestion as non-blocking if the maintainer accepts the documented risk, rather than require the cross-store transaction change in this PR. The suggested locking approach remains appropriate for a follow-up: candidate selection and removal need to share the profile-scoped lock so an import cannot commit between them.

One caveat: the gap is narrow, but not guaranteed to last only milliseconds under load. That doesn’t change the scope argument; it just means timing alone shouldn’t justify acceptance.

I haven’t changed the suggestion or its status.

@Quick104
Quick104 marked this pull request as ready for review October 8, 2026 21:07
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-08T21:21:19.899081Z c562f0d New commits
🔒 Security Review ✅ Completed 2026-10-08T21:25:16.468537Z c562f0d New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

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

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1098 to +1102
_, history := withHistory[id]
_, progress := withProgress[id]
if history || progress {
watched = append(watched, id)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve tombstones for unwatched file-less episodes

When a file-less episode has no visible history or progress at lookup time, this condition omits its ID from RemoveHistoryItems, so no hidden-history marker is written. If a partial or later history import subsequently supplies an older watch for that catalog episode, AddHistoryIfMissing finds no marker, imports the watch, and the removed show's card reappears; library-backed episodes do not have this problem because removal tombstones all of them regardless of current state. Show/season removal therefore needs a durable way to suppress pre-removal imports for every known file-less episode rather than filtering solely on currently visible state.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is deliberate. Writing a hidden-history marker for every file-less episode is what the earlier version of this PR did. A long-running show can have thousands of metadata-only episodes and only a few files, so that version wrote a permanent marker row and published a user-state event per episode on every removal.

Removal hides what the History page showed when the user removed it. A watch for a file-less episode that arrives in a later import was not on that card, so showing it is defensible. The difference from episodes with a file is real, and it is a maintainer's call. I've added it to the PR's Risks section and am leaving this thread open.

}
addMediaItems(watchedFileless)

if err := store.RemoveHistoryItems(ctx, profileID, mediaItemIDs, time.Now().UTC()); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Batch the final SQLite removal write

On the supported SQLite user-store backend, the new lookup is batched but the resulting combined ID list is passed to RemoveHistoryItems in one call. That implementation expands every ID into a SQL placeholder and adds five more parameters, so a request resolving more than roughly 32,761 IDs—such as a multi-target removal or a metadata-heavy show with many imported file-less watches—fails with SQLite's 32,766-variable limit and returns 500. This commit can introduce that failure even when the library-backed episode list was previously small; the SQLite store should execute bounded chunks within one transaction.

AGENTS.md reference: AGENTS.md:L13-L18

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The SQLite RemoveHistoryItems takes the whole list in one call, and it did before this PR. A selection with more than about 32k episodes with a file already hits the limit on main. This PR adds only the file-less episodes the profile actually watched, which is bounded by watch history, not by catalog size; the candidate lookup over all file-less episodes is the part that got batched.

Chunking the SQLite store's writes inside its transaction would fix both cases. That is a store change, so I'd keep it out of this PR. Leaving the thread open for a maintainer.

Comment thread internal/api/handlers/favorites.go Resolved
Removal listed the episodes with a library file and the file-less ones in
two statements. An episode whose first file was linked between them fell
into neither list, so a watch on it survived the removal. One query now
splits the episodes by availability.

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

silo-kody Bot commented Oct 8, 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 ❌

@macroscopeapp

macroscopeapp Bot commented Oct 8, 2026

Copy link
Copy Markdown

The file-less episode removal also changes which entries appear on the History screen at phone width, but the PR describes before-and-after web History captures without identifying phone-width captures. Please include before-and-after phone-width captures of the same seeded history state on the evidence page; API excerpts do not show the mobile screen.

Suggested fix: No diff — add the phone-width before-and-after captures to the evidence page.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@Quick104

Quick104 commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Added phone-width before-and-after captures of the History page to the evidence page, from the same seed on main and on c562f0d. On main, Partial Series stays listed after removal at phone width; on this branch it is gone.

@Quick104
Quick104 merged commit c9cacfd into main Oct 8, 2026
39 of 41 checks passed
@Quick104
Quick104 deleted the fix/issue-2164-history-remove-unlinked-episodes branch October 8, 2026 21:44
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.

[bug] Removing a show from watch history leaves its card when an episode has no file

1 participant