Repository navigation
perf(access): stop re-reading legacy settings on every profile request - #1377
Conversation
Every profile-scoped request resolved hidden libraries from the canonical ui.disabled_library_ids row and, when the profile had none (the default), also read the frozen legacy disabled_library_ids account row. Home section requests did the same for ui.next_up_mode, up to three times per request. The legacy settings endpoint stopped accepting both keys at the settings cutover, so those reads return values that can no longer change. A Go migration on Postgres and SQLite schema v26 copy each legacy value onto every profile that has no canonical row. They use the settings planner, so each stored value matches what the fallback read produced. Stored rows win, and the legacy rows stay in place. With the values materialized, the fallback reads go away. ui.next_up_mode now resolves in the same settings read as the rest of the viewer scope and rides on access.Scope (excluded from its JSON, so access fingerprints do not change), and section fetchers take it from the request scope. Measured with a MaxConns=1 pgx tracer: the auth prelude for a default profile drops from 6 to 5 statements (7 to 6 for an access-group member), and a NextUpMode call inside a request drops from 2 statements to 0. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
RequireAuth checks session validity with the SessionValidator on every request, and the production validator is an uncached query. The comments claimed an in-memory cache, which hides the per-request cost and suggests a revocation might lag. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Measure the Home half of the identity-prelude change through SectionHandler.HomeSectionItems instead of deriving it from per-call counts. With a scope from the production viewer resolver, the Continue Watching and Next Up section requests make no next-up mode reads for either mode. On the base commit the same requests made 2 to 4. Review follow-ups on the retired-fallback migration: - read both legacy keys in one pass with key = ANY($1) - log unconvertible values on SQLite, as Postgres already does - correct the comment that said user_settings will be dropped; other keys still use it Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
|
Warning Review limit reachedNext included review available in 6 minutes. View limit detailsLimit details: You’ve used all 2 included reviews currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (24)
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. Comment |
There was a problem hiding this comment.
Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
The remaining identity-prelude work (session plus user in one statement, profile and settings in one batch, target 2 round trips) is tracked in #1389. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2f3c2739ea
ℹ️ 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".
| settingsBackfillMigration(), | ||
| displayPrefsMoveMigration(), | ||
| subtitleLanguageBackfillMigration(), | ||
| retiredSettingsFallbacksMigration(), |
There was a problem hiding this comment.
Move the backfill into a Goose SQL migration
This database-changing backfill is registered only as a new Go migration, but the repository’s absolute migration rule requires new DB changes to be timestamped Goose SQL migrations under migrations/sql/. Rework this change into the required SQL migration rather than adding retiredSettingsFallbacksMigration() to the programmatic migration list.
AGENTS.md reference: AGENTS.md:L92-L100
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, and fixed in 5c0f36f. The backfill is now a Goose SQL migration, 20260924052112_materialize_retired_settings_fallbacks.sql, created with make migrate-create. The Go migration and its registration in migrate.go are removed. The SQL reproduces settingsmigrate.PlanRetiredFallback, which the SQLite user store still runs in Go at schema v26. Hidden-library lists convert only in the shape Go's JSON decoder accepts, which keeps malformed values from aborting the migration; next-up modes must be exactly combined or separate after Go-style whitespace trimming. A new DB-backed test seeds 53 accounts covering valid, empty, malformed, out-of-range, oversize and already-stored cases, and requires the migration to write exactly what the planner plans.
…migration New database changes belong in timestamped Goose SQL migrations under migrations/sql, but the retired-fallback backfill was registered as a Go migration. It now lives in 20260924052112_materialize_retired_settings_fallbacks.sql, created with make migrate-create, and the Go migration is removed. The SQL reproduces settingsmigrate.PlanRetiredFallback, which the SQLite user store still runs in Go at schema v26. A hidden-library list converts only in the shape Go's encoding/json decodes into []int; nulls and non-positive ids are dropped, repeats are removed in first-seen order, and a list of more than 512 ids is skipped. A next-up mode is trimmed of Go's Unicode whitespace and kept only when it is "combined" or "separate". Stored rows still win, legacy rows stay, and a re-run changes nothing. TestRetiredSettingsFallbacksMigrationMatchesPlanner seeds 53 accounts covering every shape the planner handles and fails if the migration writes anything other than what the planner plans. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5c0f36f74f
ℹ️ 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".
| } | ||
| return p.PlanRuntimeValue(legacyKey, string(encoded)) | ||
| case legacyNextUpModeKey: | ||
| return p.PlanRuntimeValue(legacyKey, raw) |
There was a problem hiding this comment.
Preserve the raw legacy next-up behavior
When a frozen legacy next_up_mode row contains surrounding whitespace and a profile has no canonical row, PlanRuntimeValue trims the value before storing it. Previously NextUpMode returned the legacy string unchanged, while the section fetchers compared it exactly with "separate" and "combined"; therefore a value such as " separate " did not enable the separate Next Up row, but this migration materializes "separate" and unexpectedly enables it. Convert according to the retired read path rather than the generic write normalization.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: the retired read returned the legacy string unchanged and the fetchers compared it exactly, so a padded value such as " separate " behaved as the default, while the backfill trimmed it into "separate". Fixed in b2bdbee. PlanRetiredFallback now rejects a padded next-up value before the generic normalization trims it (the SQLite v26 path skips it), and the SQL migration copies only the exact members combined and separate. A skipped value leaves the profile at the default, which is what the fallback gave it. The planner parity test now expects no row for the padded cases, and it passes against Postgres.
The retired fallback returned the legacy next_up_mode string unchanged, and the section fetchers compared it with "separate" exactly, so a padded value such as " separate " never enabled the separate Next Up row. The backfill trimmed before validating and would have written "separate" for it, turning the row on for that profile. Only an exact member is converted now. The planner rejects a padded value before the generic write normalization trims it, so the SQLite v26 path skips it, and the SQL migration matches the two members exactly. A skipped value leaves the profile at the default, which is what the fallback gave it. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b2bdbee4b9
ℹ️ 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".
| FROM user_settings s | ||
| JOIN user_profiles p ON p.user_id = s.user_id | ||
| WHERE s.key = 'next_up_mode' | ||
| AND s.value IN ('combined', 'separate') |
There was a problem hiding this comment.
Preserve invalid legacy next-up behavior
When a legacy next_up_mode contains anything other than an exact enum member—including the padded value discussed in the prior thread—this predicate writes no row, so the new resolver supplies the combined default. Before this change, NextUpMode returned the raw value: fetchContinueProgressItems appends upcoming episodes only for exact combined, while maybeInjectNextUp injects a separate row only for exact separate, so such values displayed next-up episodes in neither location. Fresh evidence after the prior fix is the unchanged exact nextUpMode == NextUpModeCombined guard in internal/sections/fetcher.go; mapping these rows to the default now unexpectedly adds episodes to Continue Watching.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and this corrects my earlier reply: a padded or unknown legacy value did not behave as the default. The fetchers matched the raw value exactly against each member, so it showed next-up in neither place. I am keeping the conversion as it is, on purpose. "Neither place" is not a state the contract can hold, and keeping it would mean restoring the per-request legacy read this PR removes. The legacy endpoint stored unvalidated strings, but first-party clients only ever wrote combined or separate, so these rows should be rare. Such profiles now get the documented default. b480246 corrects the planner and migration comments, and the Risks section now states the behavior change.
| SELECT user_id, jsonb_agg(id ORDER BY first_seen) AS value | ||
| FROM hidden | ||
| GROUP BY user_id | ||
| HAVING count(*) <= 512 |
There was a problem hiding this comment.
Keep hidden libraries when the legacy list exceeds 512 IDs
For an account whose legacy disabled_library_ids contains more than 512 distinct positive IDs, the retired fallback previously accepted the entire list because parseLibraryIDList imposed no length limit. This HAVING now suppresses the canonical row completely, and because the runtime fallback is removed in the same change, every one of those libraries becomes visible after upgrade; the SQLite planner has the same contract-validation outcome. Preserve this exceptional legacy value or retain a selective fallback rather than converting an over-limit list into no hidden libraries.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct: the retired fallback applied lists of any length, and the contract caps ui.disabled_library_ids at 512, so an over-limit legacy list is not copied and those libraries become visible. I am leaving this as it is. Reaching it takes more than 512 distinct libraries on one server, and keeping it would need a selective fallback read on every profile-scoped request, which is what this PR removes. b480246 says so in the migration comment, and the Risks section lists it.
The comments said a padded legacy next-up mode behaved as the default. It did not: the section fetchers matched the raw value exactly against each member, so a padded or unknown value showed next-up in neither place. The contract has no such state, so those profiles now get the default. Say so, and say that a hidden-library list over the contract's 512-id limit is not copied, which makes those libraries visible. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b48024675a
ℹ️ 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".
| INSERT INTO user_setting_values (user_id, key, scope, profile_id, value) | ||
| SELECT p.user_id, 'ui.disabled_library_ids', 'profile', p.id, planned.value | ||
| FROM planned | ||
| JOIN user_profiles p ON p.user_id = planned.user_id |
There was a problem hiding this comment.
Seed retired settings for profiles created after migration
When an upgraded account retains either legacy setting and creates a profile after this migration has run, this join cannot materialize a row for that new profile. The normal creation path's planInheritedLegacyUserSettings also skips both keys because keyUsesUserScope rejects these retired, unregistered keys, while this commit removes their runtime fallbacks; the new profile therefore shows previously hidden libraries and uses combined Next Up instead of inheriting the account's frozen values. Seed these values during profile creation or preserve an equivalent creation-time fallback.
AGENTS.md reference: AGENTS.md:L105-L107
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Intended, and listed under Risks ("Behavior change for profiles created after this migration"). Before this change a new profile picked up the frozen account value invisibly: the settings API reported the default while the server applied the legacy hidden libraries or next-up mode, and the user had no way to see or change why. A new profile now starts from the contract defaults, which is what its settings screen shows. Seeding the retired keys at profile creation would keep an unregistered legacy key alive in the creation path indefinitely for the same hidden effect, so I have left it out. If maintainers prefer inheritance, it belongs in profile creation as an explicit copy of the canonical values from the primary profile, not in the retired keys.
Problem
Related issue: N/A
Validation tasks: changes #1180 C1, #1181 C1, #1140 C1, #1142 C1, #1252 C9, silo-apple#322 C1, silo-apple#323 C1, silo-android#332 C1, silo-android#333 C1 (all Not run)
The multi-profile cases cover per-profile hidden libraries and next-up mode, which clients now read back as stored values. The Home and Series cases cover whether Home shows a separate Next Up row. Session validation (#1186, #1187), restricted-content access (#1180 C2, #1181 C4) and access-group policy (#1196, #1197) are unchanged.
Every profile-scoped request resolves the viewer scope before its handler runs. For a profile that never saved hidden libraries, which is most profiles, that resolution runs two settings reads: the canonical
ui.disabled_library_idsrow, then the legacy account-widedisabled_library_idsrow inuser_settings. Home layout and section requests then resolveui.next_up_modeup to three times each (maybeInjectNextUp, the Continue Watching fetcher, the Next Up fetcher), and each call also falls back to the legacynext_up_moderow.The legacy settings endpoint stopped accepting both keys at the settings cutover, so those legacy rows are frozen. Reading them on every request costs a round trip and a pool acquire for a value that cannot change. The fallback also hides a mismatch: the settings API reports the contract default for a profile that has no canonical row, while the server applies the legacy value. A user sees "no hidden libraries" in settings and still has libraries hidden.
Approach
20260924052112_materialize_retired_settings_fallbacks.sql) and SQLite user-store schema v26 copy each legacy value onto every profile on the account that has no canonical row. SQLite callssettingsmigrate.PlanRetiredFallback, which applies the fallback's parsing (malformed JSON reads as empty, non-positive ids are ignored, repeats are dropped) and then the contract's validation (unique ids, at most 512, enum membership). The Postgres migration implements the same conversion in SQL, and a DB-backed parity test checks it against the planner. So each profile resolves the same answer as before. Stored rows win (ON CONFLICT DO NOTHING), a re-run changes nothing, and the legacy rows stay inuser_settings, like every other row the cutover converted.ResolveViewerPreferencesandsections.NextUpModeno longer readuser_settings.ui.next_up_modejoins the viewer-preference resolution, which was already one query for three keys, and is carried onaccess.Scope.sections.NextUpModeanswers from the request scope when that scope belongs to the same profile, and resolves it itself otherwise, for example for a background caller. The field is taggedjson:"-"because socket tickets and progress bootstrap snapshots hash the scope's JSON as an access fingerprint. A next-up change must not invalidate them, and existing fingerprints stay byte-identical.RequireAuthcomment that claimed an in-memory session cache. There is none, and there should not be one.Alternatives considered:
What this PR does not do
This PR is the first part of shrinking the per-request identity prelude. The rest is a follow-up, kept separate because it changes the auth path and deserves its own review:
RequireAuthwould joinauth_sessionstousersunder the samerevoked_at IS NULL AND expires_at > now()predicate and put the user row in the request context.ViewerResolver.Resolvewould use that row instead of callingGetByID. A revoked session would still be refused on its next request, because nothing is cached.pgx.Batchthrough apgstoremethod. The viewer resolver would use it through an optional interface, and the SQLite store would keep the sequential path.settingsresolveneeds a way to rank candidates that were already fetched.Follow-up issue: #TBD
Before and after
RequireAuth→RequireViewerAccess→RequireProfile), default profileTestProfileScopedPreludeStatementBudget: MaxConns=1 pool with a pgx query tracer, real repositories and resolver, one requestNextUpModecall, request scope resolved by the production viewer resolver, default profileTestNextUpModeStatementBudgetPostgres: same tracer"separate"rowNextUpModecall without a request scopeTestHomeSectionItemsNextUpReadsDB:SectionHandler.HomeSectionItemswith a scope from the production viewer resolver; the tracer counts statements whose SQL or arguments namenext_up_mode"separate"row"separate"rowThe "before" numbers come from the same tests copied onto
mainand run against the same database. The statements removed from the default-profile prelude areSELECT value FROM user_settings WHERE user_id = $1 AND key = $2. This PR makes no timing claim. The saving is one round trip and one pool acquire per request, and what that is worth in wall-clock time depends on database distance and pool pressure.Validation
All checks ran on the branch after rebasing it onto current
main.go build ./...,go vet ./...andgofmt -l .(no output): pass.make lint-changed: 0 issues.GOFLAGS=-p=6 make test-go, with no test database so DB-backed tests skip: pass.make verify-settings-bindings-all verify-playback-fixtures verify-route-inventory verify-migration-ledger verify-scenario-catalogs verify-offline-routes verify-apiv2-openapi verify-apiv2-contract verify-apiv2-fixtures verify-local-paths,make migrate-validateandgo test -run '^TestCommittedArtifactMatchesRouter$' ./internal/apiv2/: pass.internal/databaseran on its own, because its migration round-trip tests roll the schema back. It passes, as dointernal/access/...,internal/api/middleware/...,internal/policy/...,internal/sections/...,internal/settingsmigrate/...,internal/userdb/...,internal/userstore/...,internal/progresssync/...,internal/jellycompat/...andinternal/apiv2/....internal/api/handlers: everything passes exceptTestAdminSubtitleListPageDBandTestCatalogTransferPersistsJobsAndSignedLink, which fail the same way onmainwithout this branch.main, they report the "before" counts.PlanRetiredFallbackplans, keep legacy rows, and change nothing on a second run. On a freshly migrated database it also rolls down to20260923203213and back up cleanly. They also cover the SQLite v25 → v26 upgrade, the planner's conversion rules,NextUpModeanswering from the scope and ignoring a scope for another profile, scope JSON unchanged byNextUpMode, and Home section-items requests making no next-up mode reads, with only the"separate"profile getting a Next Up row.TestResolveViewerScopeParitynow seeds hidden libraries as canonical rows.Risks
combinedorseparate(unknown, wrong case, or padded with whitespace). Before, the fetchers matched the raw value against each member exactly, so such a value showed next-up in neither Continue Watching nor its own row. The contract has no such state; those profiles now get the default,combined, which adds next-up episodes to Continue Watching.unsupported sqlite schema version 26).userdb/bridgeimport.ImportAccount(not wired to any command yet) copies legacy rows from a v22 SQLite store and would not materialize them. If it is ever wired up, it needs the same step.Checklist
AI Disclosure
HomeSectionItemsinstead of derived; the SQLite migration logs values it cannot convert, as Postgres does; a comment no longer saysuser_settingswill be dropped; this body now scopes the downgrade claim to Postgres and uses the standard validation-tasks line. Open for maintainers: whether to delete the legacy rows for an exact rollout (see Risks), and the follow-up issue for the rest of the prelude work.🤖 Generated with Claude Code