Skip to content

[bug] Unmarking a large series takes ~2 minutes (~16M index scans on episodes per request) #646

Closed

Description

@Quick104

What happened

Unmarking a large series (DELETE /api/v1/watched/{id}) takes ~2 minutes on a 6,375-episode series, versus ~5s to mark the same series watched. The request holds a connection the whole time and the UI button stays pending.

Measured on the dev server against EastEnders (42 seasons, 6,375 file-backed episodes, 8,421 history rows), same series, back to back:

--- POST (mark)   --- http=200 total=5.152s
--- DELETE (unmark) --- http=000 total=143.622s   (client timeout at 300s not reached; curl gave up on the response)

Repeated runs of the DELETE: 96.4s, 116.3s, 143.6s. Marking the same series is consistently 5–6s.

Note on provenance: I found this while verifying #645 (which fixes the mark path). The unmark path is untouched by that PR — recordMarkUnwatched does not appear in its diff, and git blame dates completedHistoryForTargets to 2026-05-22/06-18. This is pre-existing, not a regression from #645.

Root cause is NOT the obvious one

My first guess was that completedHistoryForTargets (internal/watchstate/service.go) is slow because it pages ListCompletedHistory 500 rows at a time — ~17 round-trips for 8,421 rows, each re-passing the full ID array. That guess is wrong, and I want to save the next person the detour.

Every individual SQL statement on this path is fast. Measured with EXPLAIN (ANALYZE, BUFFERS) against the real dev data:

  • one ListCompletedHistory page (offset 0, 500 rows, full 7,398-ID array): 52 ms
  • the user_history_hidden_items watermark upsert in RemoveHistoryItems: 177 ms (incl. 37 ms FK trigger × 7,398)
  • the user_watch_progress delete: 33 ms

17 pages × 52 ms is about 0.9s. That does not explain 143s.

The actual signal: ~16 million index scans on episodes for one request

Diffing pg_stat_user_tables.idx_scan immediately before and after a single DELETE:

episodes:                  +15,989,221
user_history_hidden_items:    +352,236
media_files:                   +25,605
user_watch_history:             +8,046
user_watch_progress:            +1,705
media_item_provider_ids:          +348

~16M index scans on episodes for ~8.4k history rows is ~1,900 scans per row. Statement logging during the request confirms the shape: 2,343 logged statements, with the slowest at 907 ms and almost everything else in the 1–10 ms range. This is a Go-side N+1 (or N×M) fan-out, not one slow query — which is why EXPLAIN on any single statement looks healthy and the endpoint still takes two minutes.

The same measurement during a mark on the identical series shows episodes: +2,584,217 — so both paths fan out, the unmark roughly 6× worse. Whatever is doing the per-item episode lookup is shared, and #645 only removed it from the mark path's identity resolution.

Why this matters

  • It is the mirror image of the bug fix(watchstate): make series mark-watched atomic and unload-proof #645 fixes. That PR made mark-watched atomic and unload-proof; unmark is still slow enough that a user will navigate away mid-request. Unmark is transactional (RemoveHistoryItems wraps its statements), so the failure mode is a hung UI rather than partial data — but a 2-minute button is its own bug.
  • A ~16M-scan request is a real load concern on a shared server, not just a latency annoyance.

Reproduction

Commands assume the repository root is the cwd, and a Silo deployment with a large series.

  1. Pick a series with thousands of file-backed episodes:
    SELECT e.series_id, mi.title, COUNT(*) AS eps
    FROM episodes e JOIN media_items mi ON mi.content_id = e.series_id
    WHERE EXISTS (SELECT 1 FROM media_files f WHERE f.episode_id = e.content_id)
    GROUP BY e.series_id, mi.title ORDER BY eps DESC LIMIT 5;
  2. Mark it watched, then time the unmark:
    curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" -X POST   -H "Authorization: Bearer $TOKEN" -H "X-Profile-Id: $PROFILE" "$BASE/api/v1/watched/$SERIES_ID"
    curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" -X DELETE -H "Authorization: Bearer $TOKEN" -H "X-Profile-Id: $PROFILE" "$BASE/api/v1/watched/$SERIES_ID"
  3. To see the fan-out, snapshot SELECT relname, idx_scan FROM pg_stat_user_tables WHERE relname='episodes' immediately before and after the DELETE.

Suggested direction (not yet validated)

Find the per-episode lookup behind the episodes fan-out and batch it, the way #645 batched ResolveHistoryIdentities and the duration lookups for the mark path. Likely candidates worth instrumenting first, in order:

  1. resolveWatchedTargets / episodeTargets in internal/api/handlers/items.go — the unmark branch calls the same target expansion as mark.
  2. Whatever populates ManualMarkResult.Entries for the local-watch-provider dispatch on unmark.
  3. internal/notifications/interest_hooks.go and any completion observers reachable from the unmark request.

Worth confirming with a CPU profile or targeted instrumentation rather than by inspection — my first read of this code produced a wrong answer, and the SQL-level evidence above contradicts the intuitive explanation.

Scope

Environment

  • Dev server, this branch's build (silo:dev-local, image a7ae1568ea5b), Postgres 18 (pgvector image).
  • Test data was seeded and fully cleaned up afterward; the series is back to 0 progress / 0 history rows.

AI Disclosure

  • Tool(s): Claude Code
  • Model(s): claude-opus-5[1m]
  • Involvement: fully AI-generated
  • Adversarial review: I filed this only after disproving my own initial hypothesis. My first explanation (the 500-row paging loop in completedHistoryForTargets) is stated above and refuted with EXPLAIN (ANALYZE) timings — the whole loop accounts for under a second of a 143-second request. Every number here is real captured output from the dev deployment; no synthesized logs or unexecuted repros. What I have not done is isolate the exact call site of the episodes fan-out, so the "suggested direction" is explicitly labelled unvalidated rather than presented as the fix.

Activity

  1. added
    bug
    on Aug 15, 2026
  2. Quick104 commented on Aug 15, 2026

    @Quick104
    ContributorAuthor

    Root cause found — and it also breaks #645 in production

    Followed up on the "suggested direction" above with instrumentation instead of inspection. Both the fan-out and an unrelated defect in #645 trace to the same place: the interestTrackingStore decorator in internal/notifications/interest_hooks.go.

    1. The episodes fan-out is InterestUpdater.resolveSeriesID

    interestTrackingStore.RemoveHistoryItems queues one mutation per media item (internal/notifications/interest_hooks.go:291):

    for _, mediaItemID := range mediaItemIDs {
        s.updater.QueueItemMutation(s.userID, profileID, mediaItemID)
    }

    QueueItemMutation is a cheap in-memory map insert, but the flush loop (internal/notifications/interest_updater.go:108) then calls resolveSeriesID per queued item — one query each:

    SELECT series_id FROM episodes WHERE content_id = $1
    UNION ALL SELECT series_id FROM seasons WHERE content_id = $1
    UNION ALL SELECT content_id FROM media_items WHERE content_id = $1 AND type = 'series'
    LIMIT 1

    For a 6,375-episode series that is 8,421 sequential resolutions that all collapse to one series_id, only to be deduped immediately afterwards by recomputeKey. The dedupe happens after the per-item query, not before.

    MarkProgressBatch and ClearProgressBatch have the identical per-item loop, which is why marking also showed +2.6M episodes scans.

    Attribution check: idle background scanning is only +449 episodes idx_scans per 45s on this server, so the ~16M measured during a single DELETE is genuinely the request, not the scanner running concurrently.

    2. Same file silently disables #645's batch write in production

    This one is more serious and I would not have found it without the SQL logs.

    interestTrackingStore embeds the interface userstore.UserStore:

    type interestTrackingStore struct {
    	userstore.UserStore
    	...
    }

    Embedding an interface only promotes the methods in that interface. Any optional-capability type assertion against the decorator therefore fails, even though the wrapped concrete store implements it. Minimal repro:

    type Base interface{ A() string }
    type Extra interface{ B() string }
    type real struct{}
    func (real) A() string { return "a" }
    func (real) B() string { return "b" }
    type deco struct{ Base }
    
    var d Base = deco{Base: real{}}
    _, ok := d.(Extra)   // false

    cmd/silo/main.go:1680 wraps the provider unconditionally when notifications are enabled, so in production userstore.MarkWatchedBatch's store.(WatchedBatchWriter) assertion fails and silently takes the per-target fallback loop — the exact code path #645 set out to remove.

    Confirmed on the dev server with statement logging, marking a 14-episode series:

    $ docker logs silo-postgres-1 | grep -c "INSERT INTO user_watch_history"
    28
    INSERT INTO user_watch_history (id, user_id, profile_id, media_item_id, watched_at, ...)
    VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
    

    Single-row VALUES inserts, one per episode — not the batched multi-row insert. #645's own tests pass because they exercise the bare store; only the wired-up server hits the decorator.

    This does not invalidate #645's live results (the transaction and keepalive behaviour verified there are real, and the fallback is still correct, just slower). It does mean the batching half of that PR is currently inert in production, and the same class of bug would silently disable any future optional-capability interface.

    Revised plan

    1. Make the decorator capability-transparent. Forward MarkWatchedBatch (and audit the other optional capabilities — VisibleHistoryAdder, HistoryVisibilityStore, SeriesEpisodeRollupStore, WatchedBatchWriter) through interestTrackingStore, with a compile-time assertion so a future capability cannot regress this silently.
    2. Batch resolveSeriesID. Resolve many item IDs to their distinct series in one query, or dedupe to distinct series before resolving, instead of one query per item then deduping.
    3. Regression test at the wired-up layer, not just the bare store — the gap that let this through.

    Picking this up now.

  3. added a commit that references this issue on Aug 16, 2026
    edd919c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions