Skip to content

fix: use MAIN_SUPABASE_DB_URL for retention backfill#1953

Merged
riderx merged 2 commits into
mainfrom
codex/fix-backfill-main-db-url
Apr 24, 2026
Merged

fix: use MAIN_SUPABASE_DB_URL for retention backfill#1953
riderx merged 2 commits into
mainfrom
codex/fix-backfill-main-db-url

Conversation

@riderx
Copy link
Copy Markdown
Member

@riderx riderx commented Apr 24, 2026

Summary (AI generated)

  • make the retention backfill script accept MAIN_SUPABASE_DB_URL for apply writes
  • prefer the main write URL over fallback direct URL names to match the backend DB selection logic
  • add focused unit coverage for the DB URL resolver

Motivation (AI generated)

The production env file used to run this script exposes the write connection as MAIN_SUPABASE_DB_URL. The backfill script ignored that variable, so --apply aborted before any rows were written even though the required database URL was already configured.

Business Impact (AI generated)

This restores the backfill path for retention metrics in production, which unblocks NRR and churn revenue chart data repair without requiring manual env rewrites or one-off commands.

Test Plan (AI generated)

  • bunx vitest run tests/backfill-retention-metrics.unit.test.ts
  • bun lint
  • bun typecheck

Generated with AI

Summary by CodeRabbit

Release Notes

  • Chores
    • Updated database connection configuration to prioritize an alternate environment variable for improved setup flexibility
  • Tests
    • Added test coverage for database URL resolution logic

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 24, 2026

Warning

Rate limit exceeded

@riderx has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 5 minutes and 45 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 5 minutes and 45 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: eecf2928-0cdc-4d60-9c4e-86cd63675823

📥 Commits

Reviewing files that changed from the base of the PR and between bfd8935 and 0e9a14f.

📒 Files selected for processing (2)
  • scripts/backfill_retention_metrics.ts
  • tests/backfill-retention-metrics.unit.test.ts
📝 Walkthrough

Walkthrough

The PR exports two database URL helper functions from the backfill retention metrics script and adjusts environment variable lookup order to prioritize MAIN_SUPABASE_DB_URL before DATABASE_URL. Corresponding unit tests verify the new export behavior and environment variable selection logic.

Changes

Cohort / File(s) Summary
Database URL Utilities Export
scripts/backfill_retention_metrics.ts
Exported getRequiredDatabaseUrl and getDatabaseUrl functions; updated URL resolution to prioritize MAIN_SUPABASE_DB_URL over DATABASE_URL; adjusted --apply error message to reference the new priority.
Test Coverage for Database URL Selection
tests/backfill-retention-metrics.unit.test.ts
Added test imports and coverage verifying getDatabaseUrl prioritizes MAIN_SUPABASE_DB_URL for apply operations and confirming getRequiredDatabaseUrl treats it as the required database URL.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

🐰 Hop hop, the URLs align,
Main Supabase takes the line,
Exports shine bright in test's design,
Database paths now intertwine!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: use MAIN_SUPABASE_DB_URL for retention backfill' is concise, specific, and directly describes the main change—prioritizing the MAIN_SUPABASE_DB_URL environment variable in the retention backfill script.
Description check ✅ Passed The PR description includes a clear summary of changes, detailed motivation explaining the production issue, business impact, and a comprehensive test plan with verification steps (vitest, lint, typecheck all marked as completed).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/fix-backfill-main-db-url

Comment @coderabbitai help to get the list of available commands and usage tips.

@codspeed-hq
Copy link
Copy Markdown
Contributor

codspeed-hq Bot commented Apr 24, 2026

Merging this PR will not alter performance

✅ 28 untouched benchmarks


Comparing codex/fix-backfill-main-db-url (0e9a14f) with main (633aeea)

Open in CodSpeed

@riderx riderx marked this pull request as ready for review April 24, 2026 11:07
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
scripts/backfill_retention_metrics.ts (1)

215-229: Avoid duplicating the DB env-key list across resolver and error message.

The key list is currently duplicated in logic and text. Centralizing it prevents drift and keeps future changes safer.

Refactor sketch
+const DATABASE_URL_ENV_KEYS = [
+  'MAIN_SUPABASE_DB_URL',
+  'DATABASE_URL',
+  'POSTGRES_URL',
+  'SUPABASE_DB_URL',
+  'SUPABASE_DB_DIRECT_URL',
+  'DIRECT_URL',
+] as const
+
 export function getRequiredDatabaseUrl(env: Record<string, string | undefined>) {
   const value = getDatabaseUrl(env)
   if (!value)
-    throw new Error('--apply requires MAIN_SUPABASE_DB_URL, DATABASE_URL, POSTGRES_URL, SUPABASE_DB_URL, SUPABASE_DB_DIRECT_URL, or DIRECT_URL so metric writes and processed-event markers are committed atomically')
+    throw new Error(`--apply requires ${DATABASE_URL_ENV_KEYS.join(', ')} so metric writes and processed-event markers are committed atomically`)
   return value
 }
 
 export function getDatabaseUrl(env: Record<string, string | undefined>) {
-  return env.MAIN_SUPABASE_DB_URL?.trim()
-    || env.DATABASE_URL?.trim()
-    || env.POSTGRES_URL?.trim()
-    || env.SUPABASE_DB_URL?.trim()
-    || env.SUPABASE_DB_DIRECT_URL?.trim()
-    || env.DIRECT_URL?.trim()
-    || null
+  for (const key of DATABASE_URL_ENV_KEYS) {
+    const value = env[key]?.trim()
+    if (value)
+      return value
+  }
+  return null
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/backfill_retention_metrics.ts` around lines 215 - 229, Declare a
single constant array (e.g., DATABASE_ENV_KEYS) containing the env key strings
now duplicated, then update getDatabaseUrl to iterate that array (return first
non-empty trimmed value or null) and update getRequiredDatabaseUrl to build its
error message using the same array (e.g., join(', ') or format with
human-readable separators) so the list of env keys is defined once and reused by
getDatabaseUrl and getRequiredDatabaseUrl; reference the existing functions
getDatabaseUrl and getRequiredDatabaseUrl when making these changes.
tests/backfill-retention-metrics.unit.test.ts (1)

375-386: Add one fallback-order regression test when MAIN_SUPABASE_DB_URL is absent.

Current assertions validate the main writer path, but not the non-main fallback order. A small extra test will guard against accidental resolver reordering.

Proposed test addition
   it.concurrent('accepts MAIN_SUPABASE_DB_URL as the required apply database url', () => {
     expect(getRequiredDatabaseUrl({
       MAIN_SUPABASE_DB_URL: 'postgres://main-writer',
     })).toBe('postgres://main-writer')
   })
+
+  it.concurrent('falls back to DATABASE_URL before direct-url env names', () => {
+    expect(getDatabaseUrl({
+      DATABASE_URL: 'postgres://database-url',
+      SUPABASE_DB_DIRECT_URL: 'postgres://direct',
+      DIRECT_URL: 'postgres://direct-legacy',
+    })).toBe('postgres://database-url')
+  })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/backfill-retention-metrics.unit.test.ts` around lines 375 - 386, Add a
regression test that covers the non-MAIN fallback ordering: when
MAIN_SUPABASE_DB_URL is absent but SUPABASE_DB_URL and SUPABASE_DB_READER are
present, assert that getDatabaseUrl(...) returns SUPABASE_DB_URL (and not
SUPABASE_DB_READER); add a similar assertion for getRequiredDatabaseUrl(...) if
that function should also prefer SUPABASE_DB_URL as the required URL. Reference
the existing getDatabaseUrl and getRequiredDatabaseUrl test cases and add the
new test alongside them to ensure resolver ordering isn't accidentally changed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@scripts/backfill_retention_metrics.ts`:
- Around line 215-229: Declare a single constant array (e.g., DATABASE_ENV_KEYS)
containing the env key strings now duplicated, then update getDatabaseUrl to
iterate that array (return first non-empty trimmed value or null) and update
getRequiredDatabaseUrl to build its error message using the same array (e.g.,
join(', ') or format with human-readable separators) so the list of env keys is
defined once and reused by getDatabaseUrl and getRequiredDatabaseUrl; reference
the existing functions getDatabaseUrl and getRequiredDatabaseUrl when making
these changes.

In `@tests/backfill-retention-metrics.unit.test.ts`:
- Around line 375-386: Add a regression test that covers the non-MAIN fallback
ordering: when MAIN_SUPABASE_DB_URL is absent but SUPABASE_DB_URL and
SUPABASE_DB_READER are present, assert that getDatabaseUrl(...) returns
SUPABASE_DB_URL (and not SUPABASE_DB_READER); add a similar assertion for
getRequiredDatabaseUrl(...) if that function should also prefer SUPABASE_DB_URL
as the required URL. Reference the existing getDatabaseUrl and
getRequiredDatabaseUrl test cases and add the new test alongside them to ensure
resolver ordering isn't accidentally changed.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9a23e875-32bc-4928-8faf-f3c6f6b207dc

📥 Commits

Reviewing files that changed from the base of the PR and between 633aeea and bfd8935.

📒 Files selected for processing (2)
  • scripts/backfill_retention_metrics.ts
  • tests/backfill-retention-metrics.unit.test.ts

@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@sonarqubecloud
Copy link
Copy Markdown

@riderx riderx merged commit 5d5e71c into main Apr 24, 2026
16 checks passed
@riderx riderx deleted the codex/fix-backfill-main-db-url branch April 24, 2026 12:28
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