Skip to content

fix(plugin): gate usage credits on active balance#2059

Merged
riderx merged 2 commits into
mainfrom
codex/fix-usage-credits-gate
May 7, 2026
Merged

fix(plugin): gate usage credits on active balance#2059
riderx merged 2 commits into
mainfrom
codex/fix-usage-credits-gate

Conversation

@riderx
Copy link
Copy Markdown
Member

@riderx riderx commented May 7, 2026

Summary (AI generated)

  • Recomputes orgs.has_usage_credits from positive, unexpired usage credit grants.
  • Keeps plugin plan validation replica-safe while failing closed for expired or exhausted credits.
  • Adds regression coverage for /updates with expired, exhausted, and active credits.

Motivation (AI generated)

has_usage_credits previously stayed true when any credit grant row existed, including consumed or expired grants. Plugin endpoints used that flag as a plan gate, allowing exhausted credit-backed orgs to keep passing billing checks.

Business Impact (AI generated)

This prevents continued plugin service access after prepaid credits are depleted or expired, protecting usage-based revenue while preserving the read-replica hot path.

Test Plan (AI generated)

  • bun run lint:backend
  • bunx eslint tests/plugin-credits-flag.test.ts
  • sqlfluff lint --dialect postgres supabase/migrations/20260507082135_active_usage_credits_flag.sql
  • bun run supabase:db:reset
  • bun run supabase:with-env -- bunx vitest run tests/plugin-credits-flag.test.ts
  • bun run supabase:with-env -- bunx vitest run tests/files-security.test.ts tests/security-definer-execute-hardening.test.ts
  • bun run supabase:with-env -- bunx vitest run tests/organization-put-stripe-sync.unit.test.ts
  • bun run typecheck

Generated with AI

Summary by CodeRabbit

  • Bug Fixes

    • Improved organization credit status tracking so active, unexpired credits are detected and plan gating correctly blocks requests when credits are absent.
  • Chores

    • Added a database migration to maintain and refresh the organization credits flag reliably.
  • Tests

    • Added regression tests covering expired, exhausted, and restored credit scenarios to ensure blocking behavior.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 7, 2026

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2a50e81f-ba68-492c-934a-e3f22dcba11e

📥 Commits

Reviewing files that changed from the base of the PR and between 8f1b6bd and b9b96c1.

📒 Files selected for processing (1)
  • supabase/migrations/20260507082135_active_usage_credits_flag.sql
🚧 Files skipped from review as they are similar to previous changes (1)
  • supabase/migrations/20260507082135_active_usage_credits_flag.sql

📝 Walkthrough

Walkthrough

This PR adds a migration and tests to derive and maintain org has_usage_credits from usage_credit_grants: a bulk refresh function, a trigger-based sync function (with trigger), migration execution that runs the refresh and updates cron metadata, and tests verifying expired/exhausted/active grant behaviors.

Changes

Usage Credits Flag Synchronization

Layer / File(s) Summary
Flag Documentation & Schema
supabase/functions/_backend/utils/pg.ts, supabase/migrations/20260507082135_active_usage_credits_flag.sql
Comments clarify has_usage_credits indicates positive, unexpired credits; migration sets column comment explaining flag semantics and replica parsing behavior via to_jsonb(...)->>'has_usage_credits'.
Flag Maintenance Functions
supabase/migrations/20260507082135_active_usage_credits_flag.sql
refresh_orgs_has_usage_credits() recomputes flag for all orgs from usage_credit_grants where credits_consumed < credits_total and expires_at is future; sync_org_has_usage_credits_from_grants() trigger recalculates flag for affected org_id on grant INSERT/UPDATE/DELETE, both update org row only when flag value changes.
Migration Execution & Scheduling
supabase/migrations/20260507082135_active_usage_credits_flag.sql
Executes refresh function once during migration to populate initial flag state; updates public.cron_tasks description for refresh_org_usage_credits_flag job; wraps all changes in explicit transaction.
Test Coverage
tests/plugin-credits-flag.test.ts
Extended afterAll cleanup to delete usage_credit_grants for test org; new test seeds expired and exhausted grants, verifies /updates are blocked with HTTP 429 and on_premise_app error, then activates grant and asserts has_usage_credits flips true.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A flag now tracks when credits shine,
with triggers quick and refresh in time,
expired grants? The gate stays closed,
but fresh credits? The updates flow!
Hop along, the tests will show.

🚥 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(plugin): gate usage credits on active balance' clearly and concisely summarizes the main change: implementing active balance validation for usage credits in the plugin plan gating logic.
Description check ✅ Passed The PR description covers the required template sections: Summary, Motivation, Business Impact, and Test Plan (with checked items showing execution). All critical information is present and adequately detailed.
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-usage-credits-gate

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 SQLFluff (4.1.0)
supabase/migrations/20260507082135_active_usage_credits_flag.sql

User Error: No dialect was specified. You must configure a dialect or specify one on the command line using --dialect after the command. Available dialects:
ansi, athena, bigquery, clickhouse, databricks, db2, doris, duckdb, exasol, flink, greenplum, hive, impala, mariadb, materialize, mysql, oracle, postgres, redshift, snowflake, soql, sparksql, sqlite, starrocks, teradata, trino, tsql, vertica


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

@codspeed-hq
Copy link
Copy Markdown
Contributor

codspeed-hq Bot commented May 7, 2026

Merging this PR will not alter performance

✅ 28 untouched benchmarks


Comparing codex/fix-usage-credits-gate (b9b96c1) with main (fd81385)

Open in CodSpeed

@riderx riderx marked this pull request as ready for review May 7, 2026 09:03
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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@supabase/migrations/20260507082135_active_usage_credits_flag.sql`:
- Around line 44-85: The function sync_org_has_usage_credits_from_grants() is
never attached to the usage_credit_grants table; add a CREATE TRIGGER that binds
this function to public.usage_credit_grants so orgs.has_usage_credits is updated
automatically on changes—create a trigger (e.g.,
sync_org_has_usage_credits_from_grants_trigger) AFTER INSERT OR UPDATE OR DELETE
ON public.usage_credit_grants FOR EACH ROW that EXECUTE FUNCTION
public.sync_org_has_usage_credits_from_grants(); ensure the trigger name is
unique and uses the same function schema/name.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5241dbec-5b30-4b9b-bdb8-44b93812cd68

📥 Commits

Reviewing files that changed from the base of the PR and between fd81385 and 8f1b6bd.

📒 Files selected for processing (3)
  • supabase/functions/_backend/utils/pg.ts
  • supabase/migrations/20260507082135_active_usage_credits_flag.sql
  • tests/plugin-credits-flag.test.ts

Comment thread supabase/migrations/20260507082135_active_usage_credits_flag.sql
@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud Bot commented May 7, 2026

@riderx riderx merged commit 8cf7cc3 into main May 7, 2026
38 checks passed
@riderx riderx deleted the codex/fix-usage-credits-gate branch May 7, 2026 10:27
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