Repository navigation
Description
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 —
recordMarkUnwatcheddoes not appear in its diff, andgit blamedatescompletedHistoryForTargetsto 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
ListCompletedHistorypage (offset 0, 500 rows, full 7,398-ID array): 52 ms - the
user_history_hidden_itemswatermark upsert inRemoveHistoryItems: 177 ms (incl. 37 ms FK trigger × 7,398) - the
user_watch_progressdelete: 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 (
RemoveHistoryItemswraps 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.
- 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;
- 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"
- 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:
resolveWatchedTargets/episodeTargetsininternal/api/handlers/items.go— the unmark branch calls the same target expansion as mark.- Whatever populates
ManualMarkResult.Entriesfor the local-watch-provider dispatch on unmark. internal/notifications/interest_hooks.goand 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
- Type: bug, performance →
fix/branch prefix. - Client surface: none. No API contract change intended — same endpoint, same response shape.
- Related: fix(watchstate): make series mark-watched atomic and unload-proof #645 (fixes the mark-watched half). Not a v1 capability epic; happy to file it under one if preferred.
Environment
- Dev server, this branch's build (
silo:dev-local, imagea7ae1568ea5b), 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 withEXPLAIN (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 theepisodesfan-out, so the "suggested direction" is explicitly labelled unvalidated rather than presented as the fix.
Activity
Quick104 commentedon Aug 15, 2026
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
interestTrackingStoredecorator ininternal/notifications/interest_hooks.go.1. The
episodesfan-out isInterestUpdater.resolveSeriesIDinterestTrackingStore.RemoveHistoryItemsqueues one mutation per media item (internal/notifications/interest_hooks.go:291):QueueItemMutationis a cheap in-memory map insert, but the flush loop (internal/notifications/interest_updater.go:108) then callsresolveSeriesIDper queued item — one query each: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 byrecomputeKey. The dedupe happens after the per-item query, not before.MarkProgressBatchandClearProgressBatchhave the identical per-item loop, which is why marking also showed +2.6Mepisodesscans.Attribution check: idle background scanning is only +449
episodesidx_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.
interestTrackingStoreembeds the interfaceuserstore.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:
cmd/silo/main.go:1680wraps the provider unconditionally when notifications are enabled, so in productionuserstore.MarkWatchedBatch'sstore.(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:
Single-row
VALUESinserts, 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
keepalivebehaviour 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
MarkWatchedBatch(and audit the other optional capabilities —VisibleHistoryAdder,HistoryVisibilityStore,SeriesEpisodeRollupStore,WatchedBatchWriter) throughinterestTrackingStore, with a compile-time assertion so a future capability cannot regress this silently.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.Picking this up now.
fix(notifications): restore store capabilities and batch series resol…