Skip to content

Make Spotify onboarding and roster attachment atomic - #83

Merged
sidneyswift merged 9 commits into
mainfrom
codex/onboarding-roster
Oct 8, 2026
Merged

sidneyswift merged 9 commits into
mainfrom
codex/onboarding-roster

Conversation

@sidneyswift

@sidneyswift sidneyswift commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Existing Spotify artists could miss organization roster attachment, and a failed new-artist attachment could leave partial records. This adds service-role-only transactions for exact Spotify resolution and legacy name-only creation, with membership checks and atomic roster relationships. Spotify lookup accepts the stored, scheme-stripped URL format and preserves case-sensitive provider identity. Conflicting mappings fail without reassignment.

Tracks recoupable/app#2166. Apply the ordered migrations through 20261008040000_recheck_spotify_social_owner.sql before deploying recoupable/api#969. No existing records are cleaned up, no global identity constraints are added, and no rights are assigned. Legacy writers outside these functions remain in recoupable/app#2119.

Validation: 18 tests passed against disposable PostgreSQL 17, including 16 concurrent calls, new/existing identity, namesakes, non-admin revocation, role privileges, lookup failure, persisted normalized social IDs, and Spotify/name-only attachment rollback. The minimal fixture loads the repository's actual social-normalization trigger migrations. GitHub Actions now runs this suite for every PR. This remains narrower than a full Supabase migration replay.

Hosted preflight found that FOR SHARE needs UPDATE on at least one membership column. The final migration grants only UPDATE(updated_at) to service_role, preserving the row lock without granting changes to membership identity columns. The fixture now mirrors the observed preview grants and proves identity mutation remains denied. No manual dashboard grant was made.

Hosted preview service-role checks passed for new/reused identity, retries, name-only creation, ambiguity rejection, and denied access, with all synthetic writes rolled back and zero fixture records remaining. Full authenticated UI → API → persisted roster verification remains pending. The latest migration also rejects ownership acquired by a concurrent legacy writer; its local two-session test verifies rollback and retry. The production OAuth migration at 010000 is preserved; onboarding starts at 020000. Merged and deployment verified; authenticated production roster acceptance remains pending. See tests/README.md for deployment order and validation boundaries.

Release evidence: recoupable/app#2166 (comment) (hosted preview checkpoint). Final production commit/deployment and verification boundaries are recorded in the latest release checkpoint on recoupable/app#2166 and #2167.

@coderabbitai

coderabbitai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9559a1c1-4d42-42fb-bc86-c20d00ad5753
  • Autopilot · 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.

@supabase

supabase Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Updates to Preview Branch (codex/onboarding-roster) ↗︎

Deployments Status Updated
Database ✅ Thu, 08 Oct 2026 01:55:46 UTC
Services ✅ Thu, 08 Oct 2026 01:55:46 UTC
APIs ✅ Thu, 08 Oct 2026 01:55:46 UTC

Tasks are run on every commit but only new migration files are pushed.
Close and reopen this PR if you want to apply changes from existing seed or migration files.

Tasks Status Updated
Configurations ✅ Thu, 08 Oct 2026 01:55:46 UTC
Migrations ✅ Thu, 08 Oct 2026 01:55:46 UTC
Seeding ✅ Thu, 08 Oct 2026 01:55:49 UTC
Edge Functions ✅ Thu, 08 Oct 2026 01:55:49 UTC

View logs for this Workflow Run ↗︎.
Learn more about Supabase for Git ↗︎.

@cubic-dev-ai cubic-dev-ai 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.

All reported issues were addressed across 4 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread .gitignore Resolved

@cubic-dev-ai cubic-dev-ai 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.

3 issues found across 5 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="supabase/migrations/20261008020000_onboard_artists_atomically.sql">

<violation number="1" location="supabase/migrations/20261008020000_onboard_artists_atomically.sql:3">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**

This migration is 114 lines, exceeding the rule’s 100-line file limit. Split the two onboarding function definitions into separate migration files or otherwise reduce the file below the limit.</violation>

<violation number="2" location="supabase/migrations/20261008020000_onboard_artists_atomically.sql:45">
P2: Exact case-sensitive equality on the extracted id silently misses legacy rows whose stored Spotify id was lowercased by the 2025-05-28 normalization backfill (`case variants of the same id exist`, per 20260729060000). A miss mints a duplicate artist account + case-variant social, and the next call hard-fails with the ambiguity error. Compare case-insensitively, and when multiple accounts differ only by URL case, raise ambiguity instead of creating.</violation>
</file>

<file name="tests/test_spotify_onboarding.py">

<violation number="1" location="tests/test_spotify_onboarding.py:145">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**

This file is 159 lines and now tests two separate functions: `onboard_spotify_artist` and the newly added `create_artist_with_roster` cases. Both exceed the 100-line file cap and the single-responsibility requirement in the repo's maintainability rules. Split the `create_artist_with_roster` tests into a dedicated test class (e.g., `NameOnlyArtistCreation`) to keep this class focused on Spotify identity resolution.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

SELECT array_agg(DISTINCT a.account_id) INTO v_candidates
FROM public.socials s
JOIN public.account_socials a ON a.social_id = s.id
WHERE substring(s.profile_url FROM '^(?:(?:https?://)?open[.]spotify[.]com/(?:intl-[a-z]{2}/)?artist/|spotify:artist:)([A-Za-z0-9]{22})(?:[/?#].*)?$') = p_spotify_artist_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: Exact case-sensitive equality on the extracted id silently misses legacy rows whose stored Spotify id was lowercased by the 2025-05-28 normalization backfill (case variants of the same id exist, per 20260729060000). A miss mints a duplicate artist account + case-variant social, and the next call hard-fails with the ambiguity error. Compare case-insensitively, and when multiple accounts differ only by URL case, raise ambiguity instead of creating.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At supabase/migrations/20261008020000_onboard_artists_atomically.sql, line 45:

<comment>Exact case-sensitive equality on the extracted id silently misses legacy rows whose stored Spotify id was lowercased by the 2025-05-28 normalization backfill (`case variants of the same id exist`, per 20260729060000). A miss mints a duplicate artist account + case-variant social, and the next call hard-fails with the ambiguity error. Compare case-insensitively, and when multiple accounts differ only by URL case, raise ambiguity instead of creating.</comment>

<file context>
@@ -0,0 +1,114 @@
+  SELECT array_agg(DISTINCT a.account_id) INTO v_candidates
+    FROM public.socials s
+    JOIN public.account_socials a ON a.social_id = s.id
+    WHERE substring(s.profile_url FROM '^(?:(?:https?://)?open[.]spotify[.]com/(?:intl-[a-z]{2}/)?artist/|spotify:artist:)([A-Za-z0-9]{22})(?:[/?#].*)?$') = p_spotify_artist_id;
+  IF cardinality(v_candidates) > 1 THEN
+    RAISE EXCEPTION 'Spotify artist identity is ambiguous; resolve the conflicting links before retrying'
</file context>

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 adopting case-insensitive identity resolution. Spotify IDs are case-sensitive; two valid IDs differing only by case must remain distinct, as the regression verifies. Historical destructive lowercasing cannot establish the original provider identity and needs source-backed repair outside this scoped onboarding fix. Matching those rows by case-insensitive guess could silently attach another artist.

artist = self.call().split('|')[0]
self.assertEqual(self.sql(f"SELECT s.profile_url FROM socials s JOIN account_socials a ON a.social_id=s.id WHERE a.account_id='{artist}'"), f'open.spotify.com/artist/{SPOTIFY}')

def test_name_only_creation_rolls_back_on_attachment_failure(self):

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: Custom agent: Enforce Clear Code Style and Maintainability Practices

This file is 159 lines and now tests two separate functions: onboard_spotify_artist and the newly added create_artist_with_roster cases. Both exceed the 100-line file cap and the single-responsibility requirement in the repo's maintainability rules. Split the create_artist_with_roster tests into a dedicated test class (e.g., NameOnlyArtistCreation) to keep this class focused on Spotify identity resolution.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/test_spotify_onboarding.py, line 145:

<comment>This file is 159 lines and now tests two separate functions: `onboard_spotify_artist` and the newly added `create_artist_with_roster` cases. Both exceed the 100-line file cap and the single-responsibility requirement in the repo's maintainability rules. Split the `create_artist_with_roster` tests into a dedicated test class (e.g., `NameOnlyArtistCreation`) to keep this class focused on Spotify identity resolution.</comment>

<file context>
@@ -129,9 +131,29 @@ def test_personal_then_organization_retry_reuses_identity(self):
+        artist = self.call().split('|')[0]
+        self.assertEqual(self.sql(f"SELECT s.profile_url FROM socials s JOIN account_socials a ON a.social_id=s.id WHERE a.account_id='{artist}'"), f'open.spotify.com/artist/{SPOTIFY}')
+
+    def test_name_only_creation_rolls_back_on_attachment_failure(self):
+        self.sql("ALTER TABLE artist_organization_ids ADD CONSTRAINT fixture_failure CHECK (false) NOT VALID")
+        try:
</file context>

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.

Keeping one transaction fixture for the shared profile and roster invariant. The applicable repository instructions do not impose a 100-line file cap; splitting this small integration harness would duplicate or obscure the shared database setup. Both commands must prove the same rollback and authorization boundary.

@@ -0,0 +1,114 @@
-- Atomic Spotify onboarding for POST /artists. No cleanup or identity reassignment.

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: Custom agent: Enforce Clear Code Style and Maintainability Practices

This migration is 114 lines, exceeding the rule’s 100-line file limit. Split the two onboarding function definitions into separate migration files or otherwise reduce the file below the limit.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At supabase/migrations/20261008020000_onboard_artists_atomically.sql, line 3:

<comment>This migration is 114 lines, exceeding the rule’s 100-line file limit. Split the two onboarding function definitions into separate migration files or otherwise reduce the file below the limit.</comment>

<file context>
@@ -0,0 +1,114 @@
+-- Atomic Spotify onboarding for POST /artists. No cleanup or identity reassignment.
+-- Deploy before the API consumer. Only the trusted API may supply p_account_id.
+CREATE OR REPLACE FUNCTION public.onboard_spotify_artist(
+  p_account_id uuid,
+  p_organization_id uuid,
</file context>

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.

Keeping the already-applied preview migration intact. The applicable repository instructions do not impose a 100-line migration cap. Forward corrections are separate ordered migrations; splitting the recorded migration solely for a line threshold would introduce migration-history drift.

Comment thread .github/workflows/artist-onboarding.yml Resolved
@sidneyswift

Copy link
Copy Markdown
Contributor Author

Hosted database acceptance now passed on the existing Supabase preview at database head d508cd1. An authenticated SQL Editor session ran the functions as service_role using synthetic records within BEGIN/ROLLBACK. Assertions verified new Spotify creation, exact-ID retry/reuse, the stored normalized social, both roster relationships, name-only response shape, ambiguity rejection, nonmember denial, and client-role execution restrictions. The final readback reported zero remaining synthetic fixture accounts.

This check found a real deployment issue: the preview service role had SELECT but lacked the UPDATE privilege required for FOR SHARE on account_organization_ids. The additional migration grants UPDATE only on updated_at; it does not grant writes to membership identity columns, INSERT, DELETE, or client roles. The disposable fixture now mirrors those table privileges; all 17 PostgreSQL tests pass. No manual dashboard grants or production data patches were made.

API and app CI passed at 098c695c and 1612cb7c respectively, including the new seven-case Chromium onboarding job. The full API suite passed before the final four-case adapter validation change, and API CI passed again after that change. Browser cases use the real mobile Header, Settings action visibility, dialog/menu/hook, and request builder with synthetic auth/HTTP; unrelated settings fields and tabs remain mocked.

This proves the deployed preview database functions, not the complete authenticated app-to-API-to-database journey or production behavior. The database must be released before the API consumer. Manual songwriter/producer roles remain tracked separately in #2136.

@cubic-dev-ai cubic-dev-ai 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.

All reported issues were addressed across 3 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread tests/test_spotify_onboarding.py Resolved

@cubic-dev-ai cubic-dev-ai 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.

1 issue found across 4 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="tests/test_spotify_onboarding.py">

<violation number="1" location="tests/test_spotify_onboarding.py:107">
P3: The test depends on catching the legacy writer inside its 2s `pg_sleep(2)` window: each poll spawns a fresh psql process, and the fixed 5s deadline leaves no margin on a loaded CI runner, so it can fail spuriously; `self.call(fails=True)` also has no subprocess timeout, so a blocked function hangs the whole suite. Widen the handshake — a 10s sleep with a 7s poll deadline keeps the assertion's window but makes the race detection robust.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

sql = f"""BEGIN; SET application_name = 'onboarding_legacy_race';
INSERT INTO socials(username,profile_url) VALUES ('{SPOTIFY}','https://open.spotify.com/artist/{SPOTIFY}');
INSERT INTO account_socials SELECT '{ARTIST}',id FROM socials;
SELECT pg_sleep(2); COMMIT;"""

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The test depends on catching the legacy writer inside its 2s pg_sleep(2) window: each poll spawns a fresh psql process, and the fixed 5s deadline leaves no margin on a loaded CI runner, so it can fail spuriously; self.call(fails=True) also has no subprocess timeout, so a blocked function hangs the whole suite. Widen the handshake — a 10s sleep with a 7s poll deadline keeps the assertion's window but makes the race detection robust.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/test_spotify_onboarding.py, line 107:

<comment>The test depends on catching the legacy writer inside its 2s `pg_sleep(2)` window: each poll spawns a fresh psql process, and the fixed 5s deadline leaves no margin on a loaded CI runner, so it can fail spuriously; `self.call(fails=True)` also has no subprocess timeout, so a blocked function hangs the whole suite. Widen the handshake — a 10s sleep with a 7s poll deadline keeps the assertion's window but makes the race detection robust.</comment>

<file context>
@@ -97,6 +99,27 @@ def test_concurrent_new_submissions(self):
+        sql = f"""BEGIN; SET application_name = 'onboarding_legacy_race';
+          INSERT INTO socials(username,profile_url) VALUES ('{SPOTIFY}','https://open.spotify.com/artist/{SPOTIFY}');
+          INSERT INTO account_socials SELECT '{ARTIST}',id FROM socials;
+          SELECT pg_sleep(2); COMMIT;"""
+        with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
+            writer = pool.submit(self.sql, sql)
</file context>

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