Skip to content

fix(userstore): delete removed history against the cutoffs just stored - #4152

Merged
Quick104 merged 2 commits into
Silo-Server:mainfrom
rangoDJ:fix/bulk-unmark-history-plan-2997
Nov 14, 2026
Merged

Quick104 merged 2 commits into
Silo-Server:mainfrom
rangoDJ:fix/bulk-unmark-history-plan-2997

Conversation

@rangoDJ

@rangoDJ rangoDJ commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #2997
Validation tasks: none

Other clients: Apple, Android and Roku N/A. The change is in the server's history delete; the API and its responses are unchanged.

Removing a long show's episodes from history first upserts a removal watermark per episode into user_history_hidden_items, then deleted the history rows with a join to that table. In the same transaction the planner still used the table's old statistics, empty for a profile that never removed history. It chose a nested loop that re-read the table for every history row. A first bulk unmark took tens of seconds; later ones were fast once statistics caught up.

This PR has no dependencies and can merge in any order.

Approach

  • raiseHistoryCutoffs (internal/userstore/pgstore/progress.go) now returns each removed item's stored removed_before, through RETURNING.
  • The history delete joins those cutoffs through unnest($3::text[], $4::timestamptz[]) instead of user_history_hidden_items, so the plan doesn't depend on that table's statistics.
  • The cutoffs are the same values the old join read, so the same rows are deleted.
  • TestPostgresRemoveHistoryItemsDeletesTheirPlaysDB is added to scripts/ci/db-contracts.txt.

Validation

  • gofmt, go vet and the changed-lines lint are clean.
  • New TestPostgresRemoveHistoryItemsDeletesTheirPlaysDB removes a show's episodes and counts the stored history rows afterwards. The existing suites check only the listing, which hides removed plays either way.
  • Negative: with the delete made to remove nothing, the new test fails (1001 plays of the removed episodes are still stored, want 0). It passes on main's delete too, so it checks the same rows go.
  • go test ./internal/userstore/... passes against Postgres 18.6.
  • Not run: a timed DELETE /api/v2/watched/{series_id} on a deployment, as in the issue; the full make test-go.

Evidence

No visible change. The evidence is the delete's plan from a standalone probe on Postgres 18.6 (WSL2): 10 shows of 5,000 episodes with history on half, 200,000 other rows, statistics collected before 5,000 watermarks are inserted in the transaction, as in the issue. EXPLAIN (ANALYZE, BUFFERS):

main This PR
Join Nested Loop, inner index scan of user_history_hidden_items 2,500 times Hash Join over the profile's history
Rows removed by join filter 6,246,278 none
Execution time 44,750.850 ms 236.628 ms
=== BEFORE: insert watermarks, then DELETE ... USING user_history_hidden_items
   ->  Nested Loop (actual time=39.893..44733.068 rows=2500.00 loops=1)
         Rows Removed by Join Filter: 6246278
         ->  Index Scan using user_history_hidden_items_pkey on user_history_hidden_items hhi (actual time=0.010..9.140 rows=2499.51 loops=2500)
 Execution Time: 44750.850 ms
=== AFTER: DELETE with the returned cutoffs, no join to user_history_hidden_items
   ->  Hash Join (actual time=183.188..227.691 rows=2500.00 loops=1)
         ->  Function Scan on c (actual time=0.288..17.892 rows=5000.00 loops=1)
 Execution Time: 236.628 ms

Risks

  • The delete passes two arrays of up to one entry per removed item. That is the same size as the ID array the statement already took.

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.

AI Disclosure

  • Harness: Claude Code (Claude desktop app, Code tab)
  • Tool(s): Claude Code; GitHub CLI; psql
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: n/a

🤖 Generated with Claude Code

Note

Fix removeHistoryItems to delete removed history using stored cutoffs

  • pgstore.PostgresUserStore.raiseHistoryCutoffs now returns a map of media-item IDs to their stored removed_before cutoffs, using an upsert with a RETURNING clause. Unmarks still return nil.
  • pgstore.PostgresUserStore.removeHistoryItems deletes history rows by matching item IDs and cutoffs through unnest, instead of joining user_history_hidden_items in the DELETE. Cleared progress is still deleted afterwards.
  • Adds a database test, TestPostgresRemoveHistoryItemsDeletesTheirPlaysDB, in history_remove_db_test.go. It covers rewatches after the removal time, other titles, and a second profile.
  • Registers the new test in the DB contract list in db-contracts.txt.
  • Behavioral Change: removed-history deletion now uses the cutoff returned per item, so rows previously kept or dropped by the join against user_history_hidden_items may be handled differently. Check removeHistoryItems and clearWatchedState in progress.go.

Macroscope summarized 280842e.

Removing a long show's episodes from history first upserts a removal
watermark per episode into user_history_hidden_items, then deleted the
history rows by joining that table. In the same transaction the planner
still saw the table's old statistics, empty for a profile that never
removed history, so it chose a nested loop that re-read the table for
every history row. At 10 shows of 5,000 episodes with history on half,
the delete took 46 s; later attempts were fast once statistics caught
up.

raiseHistoryCutoffs now returns each removed item's stored
removed_before, and the delete uses those through unnest instead of the
join. The same benchmark runs the delete in 0.24 s with a hash join over
the profile's history. The rows deleted are the same.

TestPostgresRemoveHistoryItemsDeletesTheirPlaysDB counts the stored rows
after a 2,000-episode removal; the existing suites check only the
listing, which hides removed plays either way.

Closes Silo-Server#2997

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Nov 14, 2026
@silo-kody

silo-kody Bot commented Nov 14, 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 Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

History removal now collects per-item cutoffs from the watermark upsert and uses them to delete matching history rows. A PostgreSQL test checks that targeted plays are deleted while plays for another title or profile remain.

Changes: History removal

Layer / File(s) Summary
Collect cutoffs and delete matching history
internal/userstore/pgstore/progress.go, internal/userstore/pgstore/history_remove_db_test.go, scripts/ci/db-contracts.txt
raiseHistoryCutoffs returns stored cutoffs for removals and nil for unmarks. removeHistoryItems uses the cutoffs to delete matching history rows. clearWatchedState handles the updated return value. The PostgreSQL test checks deletion and retention, and the database-contracts list includes the test.

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

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: quick104

Merge Risk: Minimal · up to 28084

History removal now deletes the same rows through a faster query, and the API and responses are unchanged. No concrete merge-blocking risk was found.

Security architecture risk: Minimal · up to 28084

The refactor preserves the existing deletion cutoffs, user and profile restrictions, and transaction boundaries. No introduced or worsened security or state-consistency risk was identified.

Pre-merge checks: Passed 2

Check name Status Explanation
Title check Passed The title names the main change: the history delete now uses the cutoffs just stored by raiseHistoryCutoffs. The raw summary and objectives confirm that removeHistoryItems now uses the returned remove…
Description check Passed The description covers the problem (a slow nested-loop plan after bulk history removal), the approach (returning removed_before via RETURNING and joining through unnest), validation steps, and risks. …
Full details: Title check

Explanation

The title names the main change: the history delete now uses the cutoffs just stored by raiseHistoryCutoffs. The raw summary and objectives confirm that removeHistoryItems now uses the returned removed_before cutoffs through unnest instead of joining user_history_hidden_items. The title is specific and concise, and it is not vague. It does not mention the performance motive, but it does not need to.

Full details: Description check

Explanation

The description covers the problem (a slow nested-loop plan after bulk history removal), the approach (returning removed_before via RETURNING and joining through unnest), validation steps, and risks. All of these relate directly to the changeset, which includes the progress.go changes, the new DB test, and the db-contracts.txt entry.

  • 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: 2b99e2ec-dc70-4691-989a-55c7afcf1ca2
Commits

Reviewing files that changed from the base of the PR and between b644da1 and bf7e4c2.

Files selected for processing: 3

  • internal/userstore/pgstore/history_remove_db_test.go
  • internal/userstore/pgstore/progress.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; 2 remain after this review.

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code impact: perf Unusable slowness on normal hardware priority: P2 Limited scope, workaround exists, or polish labels Nov 14, 2026

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

I found no defects in the change to removeHistoryItems. It deletes the same rows as before, and I reproduced the slow plan on the base. Two cleanup findings on the new test are below. I'm fixing both in a commit on this branch, so there's no need to change anything yourself.

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

The check asserts which rows the delete removes, which doesn't depend on
the batch size, so 2,000 episodes only added about two seconds to every
DB contract run. Also drop the executable bit from the file.

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

silo-kody Bot commented Nov 14, 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

Copy link
Copy Markdown
Contributor

Review summary

Reviewed head: 280842e9eb (the PR's bf7e4c2 plus one test-only commit from this review).

The change works and deletes the same rows as before. RETURNING hands back the removed_before values the old join read from user_history_hidden_items, and they're written in the same transaction under the history-cutoff lock. For a removal, GREATEST over a non-null EXCLUDED.removed_before never returns NULL, so every target item gets a cutoff. The Macroscope note that deleted plays "may differ when the hidden-items table is stale" doesn't hold: the old join read this transaction's own writes, which are the values now returned.

Plan check. I ran both delete statements on Postgres 18 with the issue's shape: 10 shows of 5,000 episodes, history on half, 200,000 other rows, statistics collected before 5,000 watermarks are inserted in the transaction.

Base This PR
Plan Nested Loop, 5,000 index probes of user_watch_history Hash Join against the unnested cutoffs
Execution time 8,213.6 ms 105.7 ms

Removing a single item still uses a nested loop over idx_user_watch_history_item_witness (0.12 ms). With 50 accounts in the table, a 5,000-item removal reads only that account's rows (13.4 ms).

Scope note. #2997 reports the slow statement on bulk unmark (DELETE /api/v2/watched/{id}). Since #3013, unmark calls ClearWatchedState and no longer runs this delete. The same slow plan still applies to removing a long show from history, which is what this PR fixes, so Closes #2997 is right.

Addressed findings (fixed in 280842e9eb):

  • The new test seeded 2,000 episodes, which took about 2 s per DB contract run without changing what it catches. It now seeds 20 and runs in 0.19 s. It still fails when the delete removes nothing and when it reaches another title.
  • The test file had the executable bit set. It's now 100644.

Tests. go test ./internal/userstore/... passes against Postgres 18. The new test passes on the base too (fails-on-base), as the PR body says: it guards which rows are deleted, not the plan, so it isn't evidence of the speedup. The plan table above is that evidence.

Remaining for maintainers. Nobody has timed a "Remove from history" of a long show on a deployment. The evidence is the statement-level plan above plus the store tests.

Validated features. No passed case on the v1.0 board covers history removal. Watch-history import reads the same cutoffs, and the upsert that writes them is unchanged apart from RETURNING. Validation tasks: none is correct.

User manual. Unaffected; nothing user-facing changes.

Other clients. N/A. The API and its responses are unchanged. Jellycompat unmark uses clearWatchedState, which this PR doesn't touch.

Fit: 9/10 · Readiness: 8/10 — conditional

  • Fit: it fixes a real slowdown at the query that causes it, with no new setting, field, or code path.
  • Readiness: the code is correct and the plan improvement reproduced. The one condition is the missing end-to-end timing on a deployment.

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

@Quick104
Quick104 merged commit f5ef81b into Silo-Server:main Nov 14, 2026
19 of 20 checks passed
@rangoDJ
rangoDJ deleted the fix/bulk-unmark-history-plan-2997 branch November 15, 2026 00:45
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: perf Unusable slowness on normal hardware priority: P2 Limited scope, workaround exists, or polish size/M 50–199 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] First bulk unmark of a large show can spend seconds rescanning watch history

2 participants