Skip to content

fix(profiles): enforce the household profile limit inside the creating transaction - #2577

Merged
Quick104 merged 2 commits into
Silo-Server:mainfrom
Rhainland:fix/2423-profile-limit-transaction
Oct 21, 2026
Merged

Quick104 merged 2 commits into
Silo-Server:mainfrom
Rhainland:fix/2423-profile-limit-transaction

Conversation

@Rhainland

@Rhainland Rhainland commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #2423
Related issue: N/A
Validation tasks: none

Two profile creations arriving at the same time on an account one below its household profile limit could both succeed, leaving the account over its limit. Profile creation counted the household before opening the write transaction. Nothing re-counted inside the transaction and no database constraint bounds profiles per account, so concurrent requests all passed the same stale count. This applies to a limit set on the account and to one inherited from its access group (#1801).

This change repeats the count inside the transaction that inserts the profile. A household that is already full gets the same 409 profile_limit_reached it gets today.

Approach

createProfileWithSettingsSync already runs the profile insert in the per-account preference-settings transaction. On Postgres that transaction holds a per-account advisory lock (pg_advisory_xact_lock), so it serializes creates on one account across every API replica; on SQLite it is BEGIN IMMEDIATE. The handler now passes the account's effective limit in, and the transaction counts the household with ListProfileIDs before inserting. No schema or store interface change was needed.

The existing check before the transaction stays. It keeps answering a full household before name_conflict, so error precedence for a single request does not change. v1 POST /profiles and v2 createProfile share this code path. jellycompat does not create profiles, and account provisioning only creates a new account's first profile.

Duplicate names under concurrency are not covered here; #343 tracks that.

Validation

  • A new Postgres integration test calls the v1 HTTP handler with a real user store and user repository and sends 12 concurrent creates on an account at limit − 1: exactly one succeeds and the rest get 409 profile_limit_reached. On main the concurrent test failed every run, with 5 to 12 of the 12 creates committing. With the fix it passed 20 runs under -race.
  • A SQLite unit test covers the re-count inside the transaction.
  • The new Postgres test is listed in scripts/ci/db-contracts.txt so the DB contracts job runs it. make test-db-contracts passed against a freshly migrated database.
  • go build, gofmt, go vet, make lint-changed, and the generated-contract, fixture, route, migration-ledger, and docs-hygiene checks passed. Web lint, format, build, and budget passed.
  • make test-go: everything passed except two jellycompat Dolby Vision strip tests, which fail the same way on unmodified main on the test machine. main CI is green at that commit.
  • make test-web: a different set of 12 to 19 tests failed on each run on a heavily loaded machine. This branch changes no web files.
  • verify-actionlint and verify-shellcheck were not run because the tools are not installed locally. This branch changes no workflow or shell files.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/pr-2577/

Native API, POST /api/v1/profiles (v2 createProfile shares the code path). An account with max_profiles: 2 and one existing profile receives two create requests at the same moment. Each build ran against its own fresh local database. Profile IDs are omitted.

Before, main at df107b7. Both creates succeed and the household ends one over its limit. All 6 runs ended this way:

POST /api/v1/profiles {"name":"Kid 1"} -> 201 {"id":"…","name":"Kid 1"}
POST /api/v1/profiles {"name":"Kid 2"} -> 201 {"id":"…","name":"Kid 2"}
GET /api/v1/profiles -> 200 count=3 ['Parent', 'Kid 1', 'Kid 2']

After, this branch at eaa23f9. One create succeeds and the other gets the existing 409. All 10 runs ended this way:

POST /api/v1/profiles {"name":"Kid 1"} -> 409 {"error": "profile_limit_reached", "message": "This account has reached its profile limit (2)"}
POST /api/v1/profiles {"name":"Kid 2"} -> 201 {"id":"…","name":"Kid 2"}
GET /api/v1/profiles -> 200 count=2 ['Parent', 'Kid 2']

Risks

Each create now takes one extra SELECT id FROM user_profiles WHERE user_id = $1 inside a transaction that already holds the account's lock. Concurrent creates on the same account wait for each other, as they already did for the settings write.

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 in T3 Code
  • Tool(s): Claude Code; Codex CLI (second reviewer)
  • Model(s): claude-opus-5-5; gpt-6.1-sol
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: independent read-only reviews of the final diff by claude-opus-5-5 and gpt-6.1-sol at medium effort; neither reported findings

Note

Fix profile-limit enforcement to recheck household size inside the creation transaction

  • The profile-limit check now runs again inside the creation transaction in ProfileHandler.createProfileWithSettingsSync, closing a check-then-write race where concurrent requests could exceed the household limit (profiles_settings_sync.go).
  • Adds the errProfileLimitReached sentinel; the handler translates it into a profile-limit conflict response (HTTP 409) instead of an internal error (profiles.go).
  • Adds a PostgreSQL concurrency test (TestCreateProfileLimitConcurrentDB) with 12 parallel requests on a household one profile below its limit, requiring exactly one success, plus a SQLite unit test and a CI contract-list entry (profiles_limit_db_test.go).
  • Behavioral Change: a concurrent request that loses the race now returns a profile-limit conflict (409) instead of an internal error; unlimited accounts bypass the in-transaction count.

Macroscope summarized 1c428dc.

@silo-triage silo-triage Bot added the size/L 200–499 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 ❌

@macroscopeapp

macroscopeapp Bot commented Oct 16, 2026

Copy link
Copy Markdown

Concurrent profile creation now returns 409 profile_limit_reached when accepting all requests would exceed the household limit (internal/api/handlers/profiles.go, internal/api/handlers/profiles_settings_sync.go); the Evidence section says there is no user-visible change and provides no evidence. Please add before-and-after API response excerpts for the same concurrent create scenario at limit − 1, with the surface and build or commit identified.

Suggested fix: No diff — add the API response evidence under ## Evidence.

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

Posted via Macroscope — Visible change evidence

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels Oct 16, 2026
@coderabbitai

coderabbitai Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 15 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: cb4fbbc3-ed28-4411-9cfd-f7a7771cc01c
📥 Commits

Reviewing files that changed from the base of the PR and between eaa23f9 and 1c428dc.

📒 Files selected for processing: 5
  • internal/api/handlers/profiles.go
  • internal/api/handlers/profiles_limit_db_test.go
  • internal/api/handlers/profiles_settings_sync.go
  • internal/api/handlers/profiles_test.go
  • scripts/ci/db-contracts.txt

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: 91fc6557-e1bc-429c-9e52-57b91a0b3965
📥 Commits

Reviewing files that changed from the base of the PR and between af7f2d6 and eaa23f9.

📒 Files selected for processing: 1
  • scripts/ci/db-contracts.txt

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

📝 Walkthrough

Profile creation now re-counts existing profiles inside the settings transaction before creating a profile. When the limit is reached, the handler returns HTTP 409 with profile_limit_reached. Tests cover sequential and concurrent creation at the limit.

Changes: Profile limit enforcement

Layer / File(s) Summary
Enforce the limit during profile creation
internal/api/handlers/profiles.go, internal/api/handlers/profiles_settings_sync.go
The handler passes the effective limit to the settings transaction. The transaction re-counts profiles before creation, and the handler maps a limit error to HTTP 409 with profile_limit_reached.
Validate profile-limit behavior
internal/api/handlers/profiles_test.go, internal/api/handlers/profiles_limit_db_test.go, scripts/ci/db-contracts.txt
Tests cover the transaction-level limit error, sequential creation at the limit, and concurrent creation when one slot remains. The database-contract list includes the sequential and concurrent tests.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant ProfileHandler
  participant createProfileWithSettingsSync
  participant SettingsTransaction
  ProfileHandler->>createProfileWithSettingsSync: Pass profile limit
  createProfileWithSettingsSync->>SettingsTransaction: Count profiles before creation
  alt Count is below limit
    SettingsTransaction-->>createProfileWithSettingsSync: Continue profile creation
  else Count meets or exceeds limit
    SettingsTransaction-->>createProfileWithSettingsSync: Return errProfileLimitReached
    createProfileWithSettingsSync-->>ProfileHandler: Return HTTP 409 profile_limit_reached
  end
Loading

Suggested reviewers: quick104

Merge Risk: ⚪ Minimal · up to eaa23

Both API versions enforce the household limit within the database transaction, and registered database tests cover concurrent creation. No identified behavior change warrants delaying merge.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 63.64% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 4 files. (1 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 Issue #2423 requires a profile-count check inside the profile-creation transaction for both user-store backends and the existing 409 profile_limit_reached result at the limit. The PR adds the recoun…
Out of Scope Changes check Passed The reported production changes implement the transactional profile-limit check from issue #2423. The tests cover sequential, concurrent, PostgreSQL, and SQLite behavior. The db-contracts.txt regist…
Title check Passed The title clearly and concisely describes the main change: enforcing the household profile limit inside the profile-creation transaction.
Description check Passed The description directly explains the concurrency problem, implementation approach, validation, risks, and scope of the profile-limit changes.
Full details: Linked Issues check

Explanation

Issue #2423 requires a profile-count check inside the profile-creation transaction for both user-store backends and the existing 409 profile_limit_reached result at the limit. The PR adds the recount in createProfileWithSettingsSync, returns errProfileLimitReached before writes, and maps it to the shared API conflict. The reported PostgreSQL concurrency tests and SQLite transaction test cover the required behavior. Concurrent name handling remains excluded under #343.

Full details: Out of Scope Changes check

Explanation

The reported production changes implement the transactional profile-limit check from issue #2423. The tests cover sequential, concurrent, PostgreSQL, and SQLite behavior. The db-contracts.txt registration supports those tests. No unrelated schema, store-interface, web, workflow, or shell changes are reported.

Full details: Docstring Coverage

Explanation

Docstring coverage is 63.64% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 4 files. (1 skipped: 1 unsupported.)

Resolution

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • 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.

@Rhainland
Rhainland force-pushed the fix/2423-profile-limit-transaction branch from af7f2d6 to eaa23f9 Compare October 16, 2026 23:45
@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 ❌

@Rhainland

Copy link
Copy Markdown
Contributor Author

Added before-and-after excerpts to the Evidence section for this case. An account with a limit of 2 and one existing profile gets two POST /api/v1/profiles requests at the same moment. On main (df107b7), both return 201 and the account ends with 3 profiles; this happened in all 6 runs. On this branch (eaa23f9), one returns 201 and the other returns 409 profile_limit_reached, leaving 2 profiles; this happened in all 10 runs. The full run output is on the linked evidence page. The branch is also rebased onto current main, and the only conflict was in scripts/ci/db-contracts.txt.

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The fix is correct, and the review found nothing that blocks merge. The recount runs after the per-account advisory lock is taken and reads through the same transaction, so concurrent creates on one account serialize across replicas. The sentinel error also survives the transaction wrapper.

Two small items, both of which I'm fixing in a commit on this branch, so there's no need to change anything yourself:

  • Merge conflict with main (blocks merge as it stands). #2817 removed TestHandleCreateProfile_EnforcesUserProfileLimit and its neighbours from profiles_test.go, and scripts/ci/db-contracts.txt gained new entries at the same spot. I'm rebasing onto main. The resolution keeps main's removals and this PR's SQLite recount test.
  • Redundant DB test (inline below).

@Quick104
Quick104 force-pushed the fix/2423-profile-limit-transaction branch from eaa23f9 to 5d01b05 Compare October 21, 2026 15:21
@Quick104

Copy link
Copy Markdown
Contributor

Review summary

Reviewed head: 5d01b05 (eaa23f9 rebased onto main, plus one test-only commit). The branch was rewritten by a rebase.

The fix is correct and ready to merge. The recount runs inside WithPreferenceSettingsTransaction. On Postgres, that transaction takes pg_advisory_xact_lock for the account before the callback runs, so ListProfileIDs sees every profile the previous lock holder committed, on any replica. On SQLite, the transaction is BEGIN IMMEDIATE. The wrapper returns the sentinel error unwrapped, and the notifications store wrapper passes the transaction through unchanged, so a full household still gets 409 profile_limit_reached. v1 and v2 both reach this through ProfileHandler.CreateProfile.

Addressed

Verification

  • On a fresh, migrated Postgres 18 database, TestCreateProfileLimitConcurrentDB failed on main in 5 of 5 runs, with 4 to 12 of 12 creates committed. It passed on this branch in 5 of 5. TestCreateProfileWithSettingsSyncRecountsLimit calls the new signature, so it doesn't build on main and doesn't count as proof by itself.
  • go test ./internal/api/handlers -run Profile, go vet, and make lint-changed pass on the rebased head.
  • A cross-provider review (Codex, gpt-6.1-sol) of the original head found nothing.
  • The evidence page was captured at eaa23f9. The runtime code is unchanged since then, so it still matches.

Remaining for maintainers: none.

Validated features: no passed case is affected.
User manual: unaffected. A single create behaves as before, and the 409 already existed.
Apple / Android / jellycompat: no follow-up needed. Clients already handle profile_limit_reached, and jellycompat doesn't create profiles.

Fit: 9/10 · Readiness: 9/10 — ready (assuming CI is green)

  • Fit: this closes a correctness gap in an existing limit at the boundary that already serializes profile creation. It adds no new surface, setting, or schema.
  • Readiness: a test that fails on main shows the fix works, and no open concern remains.

@silo-kody

silo-kody Bot commented Oct 21, 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 ❌

Rhainland and others added 2 commits October 21, 2026 12:36
…ng transaction

Profile creation compared the account's profile count with its limit before
opening the write transaction, so concurrent creates on an account one below
its limit could all pass and all commit. The count is now repeated inside the
per-account transaction that inserts the profile, which Postgres serializes
with an advisory lock across replicas and SQLite with BEGIN IMMEDIATE. A full
household still answers 409 profile_limit_reached.

Closes Silo-Server#2423
TestCreateProfileLimitConcurrentDB already creates to limit - 1, checks
that the losing requests get 409 profile_limit_reached, and checks that
the household ends at its limit.

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

Copy link
Copy Markdown
Contributor

Rebased onto current main to clear a conflict in scripts/ci/db-contracts.txt: main added the TestServerCollectionCountsFollowTheViewerDB entry in the same spot, so the file now keeps both entries. No code changes.

@Quick104
Quick104 force-pushed the fix/2423-profile-limit-transaction branch from 5d01b05 to 1c428dc Compare October 21, 2026 16:39
@silo-kody

silo-kody Bot commented Oct 21, 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 ❌

@Quick104
Quick104 merged commit 1d42762 into Silo-Server:main Oct 21, 2026
16 checks passed
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 priority: P2 Limited scope, workaround exists, or polish size/L 200–499 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Enforce the household profile limit inside the profile-creation transaction

2 participants