Skip to content

fix(notifications): key episode notification state by account and profile - #2602

Merged
Quick104 merged 2 commits into
mainfrom
fix/notification-interest-account-2597
Oct 16, 2026
Merged

Quick104 merged 2 commits into
mainfrom
fix/notification-interest-account-2597

Conversation

@Quick104

@Quick104 Quick104 commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #2597
Closes #2603
Related issue: #2598
Validation tasks: none

On a server upgraded from before profiles, every account has a profile named default. When two of those accounts follow the same series, only one of them gets new-episode notifications, they share one set of notification switches, and each account's default profile sees the other's inbox (titles, unread count, mark-read). This change keys episode notification state by account and profile, so each account's profile is notified and has an inbox of its own.

A profile ID is unique only within its account (user_profiles is keyed by (user_id, id)), but these tables and queries treated it as unique on the server:

  • profile_series_interest has the primary key (profile_id, library_id, series_id), and UpsertRows set user_id = EXCLUDED.user_id on conflict, so both accounts' interest collapsed into one row owned by one account. Fanout delivers to the row's account only.
  • The episode delivery dedupe keys (profile_id, release_event_id) and (profile_id, episode_id) would drop the second account's delivery even with separate interest rows.
  • Inbox reads, counts, mark-read, v2 paging, the websocket snapshot, and the email digest selected deliveries by profile_id alone.
  • notification_preferences had no user_id at all.

Approach

One migration plus the code that reads and writes these tables:

  • profile_series_interest gets the primary key (user_id, profile_id, library_id, series_id). Rows already carry user_id.
  • notification_deliveries gets account-leading versions of the episode dedupe keys and the inbox indexes.
  • notification_preferences gains user_id, with the primary key (user_id, profile_id). A row two accounts' profiles share is copied to each account, so every profile keeps the switches it has today. Accounts come from user_profiles and, for profiles stored outside Postgres, from the account-keyed notification tables. A row no account can be found for belongs to a deleted profile and is dropped.
  • The migration clears the interest rebuild's checkpoint. The rebuild that runs at startup then makes a full pass and writes the rows the old key collapsed.

Every delivery read, mark-read, purge, preference read and write, interest recompute and cleanup, and fanout's recipient bookkeeping now carries the account. The account comes from the request's claims in v1, v2, and the websocket. The email channel reads a profile's deliveries on the account that owns its email settings. API response shapes don't change (Preferences.UserID is not serialized), so no client changes are needed. Jellycompat doesn't serve these notifications.

notification_inbox_clocks stays keyed by profile ID. It only orders inserts, so two accounts' same-ID profiles serialize their inserts without changing either inbox's order. docs/architecture/notifications.md now states the account-and-profile rule and the tables still keyed by profile ID alone.

Validation

  • Reproduced on a dev deployment from main: after both accounts' default profiles favorited one series, there was one interest row, and a new episode reached one account.
  • After the fix, on the same deployment: the migration restored the second account's row, the next episode reached both accounts, each account's v1 and v2 inbox and unread count showed only its own deliveries, and turning notifications off on one account left the other's switches and deliveries unchanged. Server log lines confirm the fanout recipient counts.
  • Migration: applied with no invalid indexes. Down refuses while two accounts share a profile-only key. On a copy without such collisions, Down, Up, and a re-run of Up all worked. The preference backfill was checked with a shared row, a profile missing from user_profiles, and an orphan row.
  • With fix(notifications): send episode notifications only to the recipient account's devices and webhooks #2599 merged in, a fanout test where both accounts' default profiles follow one series checks that each delivery queues only its own account's webhook, web push subscription, and push device.
  • New DB test for two accounts' default profiles on one series: interest rows, deliveries, inbox, preferences, recompute, and profile purge. A reproduction test failed on main before the fix. The notifications, API v2, and notification handler suites pass against the migrated database.
  • make lint-changed, migrate-validate, verify-migrations, the API v2 OpenAPI, contract, and fixture checks, and the other Go gate checks pass. make test-go passes except TestRunStatsWithRealFFmpeg, which fails on main on the same host. With a database configured, five unrelated handler tests (plugins, subtitles, catalog transfer, local login) also fail on main.

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

Evidence

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

Surface and build: /api/v2/notifications, /api/v2/notifications/unread-count, and /api/v2/notifications/preferences. Each was requested as two accounts, each with a legacy default profile, on one dev deployment: first on main (21cdfa1), then on this PR (817ab22).

Request Before (main) After (this PR)
Account 3 GET /notifications (account 2 holds the only delivery) lists account 2's episode, unread count 1 empty, unread count 0
Account 2 GET /notifications its episode, unread count 1 its episode, unread count 1
Account 2 changes enabled with PUT /notifications/preferences account 3's enabled changes with it account 3's enabled stays as it was

The evidence page has the full request output, the fanout recipients before and after, and the migration checks.

Risks

  • Rolling deploys. Replicas still running the previous build fail interest upserts and preference saves after the migration runs, because their conflict targets no longer exist. Their profile-only inbox queries also lose their indexes, and their deletes still match both accounts. The window is the rollout. Interest repairs itself in the next rebuild; a preference save made during it fails and has to be repeated. A widened unique key can't be added beside the old one, because the old one is what blocks the second account's row.
  • Migration locks. The index builds run CONCURRENTLY. The primary-key swap on profile_series_interest and the rewrite of notification_preferences take brief exclusive locks.
  • Rollback. Down refuses, without deleting anything, once two accounts hold rows under one profile ID. Stop notification writers before rolling back.
  • Upgrade window. Until the startup rebuild finishes, an account whose interest row was collapsed is still not notified, as on main today.

Follow-ups:

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; Codex CLI through T3 Code for the cross-provider review
  • Model(s): claude-opus-5-5 (implementation and code review), claude-sonnet-5-5 (one code-review finder), gpt-6.1-sol (plan review)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: Before implementation, Codex (gpt-6.1-sol, xhigh) attacked the plan. It added the live preference writer and the v2 paging methods, account-scoped email digest reads, the rebuild-checkpoint reset, concurrent index builds with re-run safety, and a rollback that refuses instead of deleting. A multi-agent code review (correctness, contract and failure, cleanup) then led to the wider preference backfill, account keys in JSON logs, rollback cleanup of invalid indexes, and an id tiebreak on the unread index. The rolling-deploy findings are listed under Risks, and the email-settings finding became [bug] Two accounts' same-ID profiles share one email notification setting, address included #2600. A background adversarial review (Codex, gpt-6.1-sol) of 4e73952 found no issues.

🤖 Generated with Claude Code

Note

Key notification state by account and profile instead of profile ID only

  • Profile IDs are not globally unique, so two accounts using the same profile ID previously shared interests, deliveries, preferences, and read state. This PR scopes all notification state to the (user ID, profile ID) pair.
  • Introduces a profileKey identity type in interest_updater.go and threads it through the fanout worker, delivery and preference repositories, email digest channel, inbox pagination, and the API handlers in notifications.go.
  • Adds migration 20261016161203_notification_state_account_key.sql that rebuilds interest, delivery, and preference indexes/keys on the composite identity, copies existing preference rows to each matching account/profile pair, and clears the interest rebuild marker so the backfill restarts.
  • New integration tests in account_scope_db_test.go verify separate interests, deliveries, read state, preferences, fanout targets, and cleanup for two accounts sharing a profile ID.
  • Risk: the migration runs non-transactionally (concurrent index builds) and its Down path refuses to roll back when multiple accounts share a profile-only key — check the invalid-index cleanup and idempotent-rerun logic in the migration. Webhook and web-push deletion calls in System.PurgeProfile remain profile-ID scoped.
  • Behavioral Change: many DeliveryRepository, PreferencesRepository, InterestRepository, and handler methods now require a user ID argument; in-tree callers are updated.

Macroscope summarized 817ab22.

…file

A profile ID is unique only within its account, and every account from
before profiles has a profile named "default". Interest rows, notification
preferences, the episode delivery dedupe keys, and inbox reads were keyed
by profile ID alone, so two accounts' "default" profiles that followed the
same series shared one interest row and only one of them was notified,
shared one set of switches, and each could see the other's inbox.

Key all of it by (user_id, profile_id): a migration widens the interest
primary key, adds user_id to notification_preferences (copying a shared
row to every account that has the profile), and re-keys the delivery
dedupe and inbox indexes, and every read, mark-read, purge, fanout lookup,
and the email channel now carry the account. The migration restarts the
interest rebuild so its startup pass restores rows the old key collapsed.

Closes #2597

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

silo-kody Bot commented Oct 16, 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 16, 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: b07b3b63-1a7e-4218-9426-1020fdca1769
📥 Commits

Reviewing files that changed from the base of the PR and between 21cdfa1 and 817ab22.

📒 Files selected for processing: 27
  • docs/architecture/notifications.md
  • internal/api/handlers/events_ws.go
  • internal/api/handlers/notification_inbox_service.go
  • internal/api/handlers/notifications.go
  • internal/api/handlers/notifications_apple_display_test.go
  • internal/apiv2/notification_inbox.go
  • internal/apiv2/notification_inbox_test.go
  • internal/notifications/account_scope_db_test.go
  • internal/notifications/delivery_repo.go
  • internal/notifications/email_digest.go
  • internal/notifications/email_prefs_repo.go
  • internal/notifications/fanout_logic_test.go
  • internal/notifications/fanout_snapshot_test.go
  • internal/notifications/fanout_worker.go
  • internal/notifications/inbox_pages.go
  • internal/notifications/inbox_pages_test.go
  • internal/notifications/interest_repo.go
  • internal/notifications/interest_updater.go
  • internal/notifications/notified_series.go
  • internal/notifications/notified_series_db_test.go
  • internal/notifications/preferences_repo.go
  • internal/notifications/recipient_access_db_test.go
  • internal/notifications/release_types.go
  • internal/notifications/request_notifier.go
  • internal/notifications/request_notifier_test.go
  • internal/notifications/system.go
  • migrations/sql/20261016161203_notification_state_account_key.sql

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

📝 Walkthrough

Notification state and delivery operations now distinguish profiles by account. Inbox API calls pass the authenticated account ID through to account-scoped queries. A database migration updates notification keys and indexes, and tests cover accounts that use the same profile ID.

Changes: Account-scoped notifications

Layer / File(s) Summary
Account keys and migration
migrations/sql/20261016161203_notification_state_account_key.sql, internal/notifications/release_types.go, internal/notifications/preferences_repo.go, docs/architecture/notifications.md
The migration adds account-scoped notification keys and indexes, migrates preference rows, and checks for collisions during rollback. Preference operations use account/profile keys. The documentation describes account-scoped state and profile-keyed exceptions.
Interest maintenance and fanout
internal/notifications/interest_repo.go, internal/notifications/interest_updater.go, internal/notifications/fanout_worker.go, internal/notifications/*test.go, internal/notifications/system.go, internal/notifications/notified_series.go
Interest updates, cleanup, preference lookups, and fanout recipient matching use account/profile keys. Database tests cover two accounts with the same profile ID and their notification targets.
Inbox repository and API access
internal/notifications/delivery_repo.go, internal/notifications/inbox_pages.go, internal/api/handlers/*, internal/apiv2/notification_inbox.go, internal/apiv2/notification_inbox_test.go
Inbox queries, read operations, and counts filter on account and profile. API handlers pass the authenticated account ID to inbox and preference operations. Tests check account-scoped access.
Email and request recipient operations
internal/notifications/email_digest.go, internal/notifications/email_prefs_repo.go, internal/notifications/request_notifier.go, internal/notifications/request_notifier_test.go, internal/notifications/system.go
Email recipient operations and request notification preference checks use account/profile keys. Profile purging deletes state for the specified account and profile.

Priority: ➖ Normal

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

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 817ab

No actionable issue remains that would prevent merging after normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 51.72% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 29 functions across 25 files. (2 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed The PR meets the coding requirements in #2597 and #2603. For #2597, the migration keys interest rows by (user_id, profile_id, library_id, series_id) and resets the interest rebuild checkpoint. Inter…
Out of Scope Changes check Passed The changes stay within the linked notification-isolation scope. The migration, repository changes, fanout recipient bookkeeping, email delivery lookup, documentation, and account-collision tests supp…
Description check Passed The description clearly explains the account-and-profile scoping change, migration, validation, risks, and follow-up work.
Title check Passed The title clearly and concisely identifies the main change: keying episode notification state by account and profile.
Full details: Linked Issues check

Explanation

The PR meets the coding requirements in #2597 and #2603. For #2597, the migration keys interest rows by (user_id, profile_id, library_id, series_id) and resets the interest rebuild checkpoint. Interest upsert, stale-row cleanup, series listing, last-notified updates, purge, fanout recipient tracking, and preference access carry the account. Delivery dedupe keys also include the account. For #2603, delivery reads, paging, lookup, unread counts, mark-read operations, websocket snapshots, and preference reads and writes filter by both account and profile. The migration copies preferences to each matching account and adds the composite key. TestSameProfileIDOnTwoAccounts covers separate interests, deliveries, inbox state, preferences, recomputation, and purge. The reported notification and API v2 test suites pass.

Full details: Out of Scope Changes check

Explanation

The changes stay within the linked notification-isolation scope. The migration, repository changes, fanout recipient bookkeeping, email delivery lookup, documentation, and account-collision tests support account/profile isolation or its safe data transition. The PR does not claim to implement destination management or email-settings ownership changes tracked by follow-up issues. The profile-only inbox clock remains an insert-ordering mechanism and does not select another account's deliveries.

Full details: Docstring Coverage

Explanation

Docstring coverage is 51.72% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 29 functions across 25 files. (2 skipped: 2 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · 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.

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code impact: security Auth, privacy, or permission boundary priority: P0 Fix/merge first: data-loss, security, or widespread breakage labels Oct 16, 2026
Comment thread internal/notifications/fanout_worker.go Resolved
Comment on lines +117 to +124
SELECT user_id, id AS profile_id FROM public.user_profiles
UNION SELECT user_id, profile_id FROM public.profile_series_interest
UNION SELECT user_id, profile_id FROM public.notification_deliveries
UNION SELECT user_id, profile_id FROM public.notification_email_prefs
) owner ON owner.profile_id = np.profile_id
JOIN public.users u ON u.id = owner.user_id
WHERE np.user_id IS NULL;
DELETE FROM public.notification_preferences WHERE user_id IS NULL;

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 critical

Preference loss occurs in migrations/sql/20261016161203_notification_state_account_key.sql because the migration deletes live SQLite profiles' settings when their account/profile pair is absent from the PostgreSQL ownership-source tables; a SQLite-only profile with notifications disabled and no interest, delivery, or email rows loses its preference row and subsequently receives all-enabled defaults. Preserve unresolved preferences for backfill against the configured user store instead of treating absent PostgreSQL ownership as proof of profile deletion.

Prompt for LLM

File migrations/sql/20261016161203_notification_state_account_key.sql:

Line 117 to 124:

Preference loss occurs in `migrations/sql/20261016161203_notification_state_account_key.sql` because the migration deletes live SQLite profiles' settings when their account/profile pair is absent from the PostgreSQL ownership-source tables; a SQLite-only profile with notifications disabled and no interest, delivery, or email rows loses its preference row and subsequently receives all-enabled defaults. Preserve unresolved preferences for backfill against the configured user store instead of treating absent PostgreSQL ownership as proof of profile deletion.

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.

Not changing this. The SQLite user store is not a live configuration (maintainer decision for this change). On the Postgres user store, user_profiles lists every profile, so a preference row whose profile_id matches no account in user_profiles, profile_series_interest, notification_deliveries, or notification_email_prefs belongs to a deleted profile. The new primary key needs an account, so such a row can't be kept as it is. Leaving this open for a maintainer in case SQLite support should block the migration instead.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Understood. My critical warning assumed SQLite was a supported live user store. Given the stated PostgreSQL-only scope and your clarification that user_profiles contains every live profile, that failure scenario does not apply. A preference row with no matching live owner can be dropped rather than assigned an invented account.

This finding does not justify a required code change under that scope. Leaving the discussion open for a maintainer to decide whether SQLite support should block the migration is reasonable; the original warning should not be treated as an unconditional critical bug.

Resolve the fanout conflicts with #2599, reuse its profileKeyArrays for
GuardedSetLastNotified and PreferencesRepository.GetMany, and add a fanout
test where both accounts' "default" profiles follow one series and each
delivery queues only its own account's webhook, web push subscription,
and push device.

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

macroscopeapp Bot commented Oct 16, 2026

Copy link
Copy Markdown

Evidence is incomplete for these visible changes:

  • Inbox membership and unread/read isolation (internal/notifications/delivery_repo.go, internal/notifications/inbox_pages.go): the linked page is described as containing before-and-after API excerpts, but the PR body does not say they use the same account/profile inbox request. The page should show the same request before and after for both accounts, including unread counts.
  • Preference isolation (internal/notifications/preferences_repo.go, internal/notifications/inbox_pages.go): the Evidence section does not identify evidence showing that changing one account's notification preferences leaves the other account's preferences unchanged. The page should include before-and-after preference API results for both accounts.

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

Posted via Macroscope — Visible change evidence

@Quick104
Quick104 merged commit f2347ac into main Oct 16, 2026
20 checks passed
@Quick104
Quick104 deleted the fix/notification-interest-account-2597 branch October 16, 2026 21:47
@macroscopeapp

macroscopeapp Bot commented Oct 16, 2026

Copy link
Copy Markdown

The Validation tasks: none line is incomplete. This change reaches the Notifications inbox/preferences and request-availability delivery paths, plus the profile-preference isolation cases. Every relevant task result is currently Not run, so there are no recorded passes to invalidate or failed/blocked cases to unblock; these cases should be tracked for validation on a published build. Please replace the line with:

Validation tasks: changes #1234 C1, C4; changes #1235 C1, C2; changes Silo-Server/silo-apple#336 C1; changes Silo-Server/silo-android#346 C1, C2; changes #1202 C3; changes #1204 C2; changes Silo-Server/silo-apple#328 C2; changes Silo-Server/silo-apple#329 C2; changes Silo-Server/silo-android#338 C2; changes Silo-Server/silo-android#339 C2; changes #1180 C1; changes #1181 C1; changes Silo-Server/silo-android#332 C1; changes Silo-Server/silo-android#333 C1

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

Posted via Macroscope — v1 validation impact

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: security Auth, privacy, or permission boundary priority: P0 Fix/merge first: data-loss, security, or widespread breakage size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority.

Projects

None yet

1 participant