Skip to content

perf(access): stop re-reading legacy settings on every profile request - #1377

Merged
Quick104 merged 6 commits into
mainfrom
perf/auth-identity-prelude
Sep 24, 2026
Merged

Quick104 merged 6 commits into
mainfrom
perf/auth-identity-prelude

Conversation

@Quick104

@Quick104 Quick104 commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

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_ids row, then the legacy account-wide disabled_library_ids row in user_settings. Home layout and section requests then resolve ui.next_up_mode up to three times each (maybeInjectNextUp, the Continue Watching fetcher, the Next Up fetcher), and each call also falls back to the legacy next_up_mode row.

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

  1. Materialize the fallback, then delete it. A Goose SQL migration on Postgres (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 calls settingsmigrate.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 in user_settings, like every other row the cutover converted.
  2. With the values in place, ResolveViewerPreferences and sections.NextUpMode no longer read user_settings.
  3. ui.next_up_mode joins the viewer-preference resolution, which was already one query for three keys, and is carried on access.Scope. sections.NextUpMode answers 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 tagged json:"-" 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.
  4. A separate commit corrects the RequireAuth comment that claimed an in-memory session cache. There is none, and there should not be one.

Alternatives considered:

  • A cache for the viewer scope or the settings reads. Rejected: replicas would disagree after a change, and revocations and policy edits would stop taking effect on the next request.
  • A Go migration that calls the planner directly, as the SQLite path does. Rejected: new Postgres schema and data changes go in timestamped Goose SQL migrations. The SQL instead matches only input that Go's JSON decoder accepts before it casts anything, so a malformed legacy value cannot abort the migration, and the parity test covers the contract rules it reimplements.
  • Deleting the legacy rows. That would make a rolling upgrade exact: old replicas would find nothing to fall back to. It also destroys data that the down migration cannot restore. Keeping the rows matches the cutover's handling of every other legacy row, and the effect on a rolling upgrade is small (see Risks).

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:

  • Validate the session and load the user in one statement. RequireAuth would join auth_sessions to users under the same revoked_at IS NULL AND expires_at > now() predicate and put the user row in the request context. ViewerResolver.Resolve would use that row instead of calling GetByID. A revoked session would still be refused on its next request, because nothing is cached.
  • Load the profile, its allowed libraries, and the settings candidates in one pgx.Batch through a pgstore method. The viewer resolver would use it through an optional interface, and the SQLite store would keep the sequential path. settingsresolve needs a way to rank candidates that were already fetched.
  • Together these take a default profile's prelude from 5 statements to 2 round trips. The tracer test would then need to count batches as round trips.

Follow-up issue: #TBD

Before and after

Metric Before After How measured
Postgres statements in the auth prelude (RequireAuth → RequireViewerAccess → RequireProfile), default profile 6 5 TestProfileScopedPreludeStatementBudget: MaxConns=1 pool with a pgx query tracer, real repositories and resolver, one request
Same, profile with a stored hidden-libraries row 5 5 same test
Same, access-group member 7 6 same test
Statements per NextUpMode call, request scope resolved by the production viewer resolver, default profile 2 0 TestNextUpModeStatementBudgetPostgres: same tracer
Same, profile with a stored "separate" row 1 0 same test
Statements per NextUpMode call without a request scope 2 1 same test
Next-up mode reads per Home section-items request, Continue Watching row, default profile 4 0 TestHomeSectionItemsNextUpReadsDB: SectionHandler.HomeSectionItems with a scope from the production viewer resolver; the tracer counts statements whose SQL or arguments name next_up_mode
Same, Next Up row requested by a default profile (not found, no row injected) 2 0 same test
Same, Continue Watching row, profile with a stored "separate" row 2 0 same test
Same, Next Up row, profile with a stored "separate" row 2 0 same test

The "before" numbers come from the same tests copied onto main and run against the same database. The statements removed from the default-profile prelude are SELECT 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 ./... and gofmt -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-validate and go test -run '^TestCommittedArtifactMatchesRouter$' ./internal/apiv2/: pass.
  • DB-backed tests against a scratch Postgres 18 database migrated to the branch head. internal/database ran on its own, because its migration round-trip tests roll the schema back. It passes, as do internal/access/..., internal/api/middleware/..., internal/policy/..., internal/sections/..., internal/settingsmigrate/..., internal/userdb/..., internal/userstore/..., internal/progresssync/..., internal/jellycompat/... and internal/apiv2/....
  • DB-backed internal/api/handlers: everything passes except TestAdminSubtitleListPageDB and TestCatalogTransferPersistsJobsAndSignedLink, which fail the same way on main without this branch.
  • The three guard tests reproduce the table. On the branch they pass at the "after" budgets; copied onto main, they report the "before" counts.
  • New tests cover the Postgres SQL migration against the planner: 53 seeded accounts cover valid, empty, malformed, non-integer, out-of-int64 and oversize hidden-library lists, padded, unknown and wrong-case next-up modes, stored canonical rows, and an account without profiles. The migration must write exactly the rows PlanRetiredFallback plans, keep legacy rows, and change nothing on a second run. On a freshly migrated database it also rolls down to 20260923203213 and back up cleanly. They also cover the SQLite v25 → v26 upgrade, the planner's conversion rules, NextUpMode answering from the scope and ignoring a scope for another profile, scope JSON unchanged by NextUpMode, and Home section-items requests making no next-up mode reads, with only the "separate" profile getting a Next Up row. TestResolveViewerScopeParity now seeds hidden libraries as canonical rows.

Risks

  • Behavior change for requests without a profile. They used to hide the account's legacy hidden libraries. Hidden libraries are now purely profile-scoped, so those requests hide nothing. This only affects accounts that saved the setting before the settings cutover, and it is a browsing preference, not an access control. Library restrictions (account, access group, profile) are unchanged.
  • Behavior change for profiles created after this migration. They no longer pick up the frozen legacy values. Before, they picked them up invisibly: the settings API showed the default while the server applied the legacy value.
  • Rolling upgrade. Old replicas still consult the legacy row, but only for a profile with no canonical row. After the migration, that is a profile created or reset while old replicas are still serving, or a request without a profile. For that window, an old replica can apply the legacy hidden libraries or next-up mode where a new replica would not. Nothing diverges after the rollout finishes. If maintainers want an exact rollout instead, the same migration can delete the two retired keys' legacy rows once it has copied them. Nothing writes those keys anymore, but the rows are also the only downgrade source.
  • Legacy values the contract cannot hold are not copied, on either backend, and those profiles get the contract default. SQLite logs them; the Postgres migration skips them without a log line. The legacy endpoint stored settings as unvalidated strings, but first-party clients only wrote valid values, so these rows should be rare:
    • A next-up mode that is not exactly combined or separate (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.
    • A hidden-library list with more than 512 distinct ids, the contract limit. The fallback applied lists of any length. Keeping one would need a selective fallback read on every request, which is what this change removes, and a server would need more than 512 libraries to reach it. Those libraries become visible.
  • Downgrade. On Postgres the down migration is a no-op: the copied rows equal what an old binary's fallback derives from the untouched legacy rows, so a downgraded server resolves the same answers. SQLite user stores cannot be downgraded: like every SQLite schema bump, v26 makes an older binary refuse to open the store (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

  • I read and can explain the complete diff.
  • This pull request addresses one concern.

AI Disclosure

  • Harness: Claude Code, running in T3 Code
  • Tool(s): Claude Code built-in tools (shell, file read/edit, Workflow subagents), GitHub CLI (gh)
  • Model(s): claude-opus-5-5[1m] for the main session and all subagents
  • Involvement: Fully AI-generated; maintainer review pending
  • Adversarial review: a separate reviewer subagent (claude-opus-5-5) reviewed the full diff, re-measured every before/after number on a fresh database with the base commit in a separate worktree, ran the goose down-and-up path on seeded legacy rows, and re-ran the affected DB-backed packages. It found no blockers or major issues. Resolved: the Home section figure is now measured through HomeSectionItems instead of derived; the SQLite migration logs values it cannot convert, as Postgres does; a comment no longer says user_settings will 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

Quick104 and others added 3 commits September 24, 2026 02:56
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>
@coderabbitai

coderabbitai Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Next included review available in 6 minutes.

Check out review usage here.

View limit details

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

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 4f694909-6e7a-467e-b895-0b6105377966

📥 Commits

Reviewing files that changed from the base of the PR and between d4e35ba and b480246.

📒 Files selected for processing (24)
  • internal/access/metadata_language.go
  • internal/access/resolver.go
  • internal/access/resolver_test.go
  • internal/access/types.go
  • internal/access/viewer_preferences.go
  • internal/access/viewer_preferences_strict_test.go
  • internal/api/handlers/home_next_up_reads_db_test.go
  • internal/api/middleware/auth.go
  • internal/api/middleware/identity_prelude_db_test.go
  • internal/database/dolby_vision_probe_migration_test.go
  • internal/database/retired_settings_fallbacks_migration_test.go
  • internal/policy/scope_parity_test.go
  • internal/policy/viewer_resolver.go
  • internal/policy/viewer_resolver_test.go
  • internal/sections/next_up_mode.go
  • internal/sections/next_up_mode_db_test.go
  • internal/sections/next_up_mode_test.go
  • internal/settingsmigrate/retired_fallbacks.go
  • internal/settingsmigrate/retired_fallbacks_test.go
  • internal/userdb/migrate.go
  • internal/userdb/migrate_v26_test.go
  • internal/userdb/setting_values_migrate.go
  • internal/userstore/pgstore/viewer_snapshot.go
  • migrations/sql/20260924052112_materialize_retired_settings_fallbacks.sql

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.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-24T06:59:46.053094Z b480246 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Quick104

Copy link
Copy Markdown
Contributor Author

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread internal/database/migrate.go Outdated
settingsBackfillMigration(),
displayPrefsMoveMigration(),
subtitleLanguageBackfillMigration(),
retiredSettingsFallbacksMigration(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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.

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>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

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.

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>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

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.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

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.

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>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

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.

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.

@Quick104
Quick104 merged commit c6a0ba9 into main Sep 24, 2026
17 checks passed
@Quick104
Quick104 deleted the perf/auth-identity-prelude branch September 24, 2026 14:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant