Skip to content

fix(meteredentitlement): fix extra grant recurrences on in-period activity changes - #4252

Merged
GAlexIHU merged 1 commit into
mainfrom
fix/entitlement-recurrence-balance
Apr 29, 2026
Merged

GAlexIHU merged 1 commit into
mainfrom
fix/entitlement-recurrence-balance

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Fixes bug where recurrence was reapplied for other in-period activity changes

Verification

To assess possible impact (exact calc would need usage data as well) something similar to this query can be run
BEGIN READ ONLY;
SET LOCAL statement_timeout = '20s';
SET LOCAL lock_timeout = '1s';

WITH params AS (
  SELECT
    now() - interval '90 days' AS since,
    now() AS until
),

activity AS MATERIALIZED (
  -- start with grant creation; add expires/deletes later if needed
  SELECT
    g.namespace,
    g.owner_id AS entitlement_id,
    g.id AS event_grant_id,
    g.effective_at AS event_at,
    g.amount::numeric AS event_grant_amount
  FROM grants g, params p
  WHERE g.effective_at >= p.since
    AND g.effective_at < p.until
),

recurring AS MATERIALIZED (
  SELECT
    rg.namespace,
    rg.owner_id AS entitlement_id,
    rg.id AS recurring_grant_id,
    rg.amount::numeric AS recurring_amount,
    rg.priority AS recurring_priority,
    rg.effective_at,
    rg.expires_at,
    rg.recurrence_anchor,
    rg.recurrence_period,
    CASE rg.recurrence_period
      WHEN 'P1D' THEN interval '1 day'
      WHEN 'P1W' THEN interval '1 week'
      WHEN 'P1M' THEN interval '1 month'
      WHEN 'P1Y' THEN interval '1 year'
      WHEN 'DAY' THEN interval '1 day'
      WHEN 'WEEK' THEN interval '1 week'
      WHEN 'MONTH' THEN interval '1 month'
      WHEN 'YEAR' THEN interval '1 year'
    END AS recurrence_step
  FROM grants rg
  JOIN (SELECT DISTINCT namespace, entitlement_id FROM activity) a
    ON a.namespace = rg.namespace
   AND a.entitlement_id = rg.owner_id
  WHERE rg.recurrence_period IS NOT NULL
    AND rg.recurrence_anchor IS NOT NULL
    AND rg.deleted_at IS NULL
    AND rg.voided_at IS NULL
),

suspect AS (
  SELECT
    a.namespace,
    e.customer_id,
    e.feature_key,
    a.entitlement_id,
    r.recurring_grant_id,
    r.recurring_amount,
    r.recurring_priority,
    a.event_grant_id,
    a.event_at,
    a.event_grant_amount,

    lr.recurred_at,
    lr.recurred_at + r.recurrence_step AS next_recurrence_at
  FROM activity a
  JOIN recurring r
    ON r.namespace = a.namespace
   AND r.entitlement_id = a.entitlement_id
   AND r.recurring_grant_id <> a.event_grant_id
  JOIN entitlements e
    ON e.namespace = a.namespace
   AND e.id = a.entitlement_id

  CROSS JOIN LATERAL (
    SELECT max(x) AS recurred_at
    FROM generate_series(
      r.recurrence_anchor,
      a.event_at,
      r.recurrence_step
    ) AS x
    WHERE x < a.event_at
      AND x >= r.effective_at
  ) lr

  WHERE lr.recurred_at IS NOT NULL
    AND (r.expires_at IS NULL OR lr.recurred_at < r.expires_at)
    AND a.event_at < lr.recurred_at + r.recurrence_step
    AND NOT EXISTS (
      SELECT 1
      FROM usage_resets ur
      WHERE ur.namespace = a.namespace
        AND ur.entitlement_id = a.entitlement_id
        AND ur.reset_time > lr.recurred_at
        AND ur.reset_time <= a.event_at
    )
)

SELECT
  namespace,
  customer_id,
  feature_key,
  entitlement_id,
  recurring_grant_id,
  min(recurred_at) AS first_suspect_recurrence,
  max(event_at) AS latest_suspect_activity,
  count(*) AS suspect_refill_events,
  sum(recurring_amount) AS rough_upper_bound_credits,
  jsonb_agg(
    jsonb_build_object(
      'recurred_at', recurred_at,
      'event_at', event_at,
      'event_grant_id', event_grant_id,
      'event_grant_amount', event_grant_amount,
      'recurring_amount', recurring_amount,
      'next_recurrence_at', next_recurrence_at
    )
    ORDER BY event_at
  ) AS intervals_for_usage_check
FROM suspect
GROUP BY namespace, customer_id, feature_key, entitlement_id, recurring_grant_id
ORDER BY rough_upper_bound_credits DESC
LIMIT 100;

ROLLBACK;

For flagged entitlements clear any balance_snapshots so history can recalculate

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Resolved an issue where recurring grant balances were being incorrectly reapplied when activity changes occurred after grant establishment.
  • Tests

    • Added regression test to prevent recurrence of this issue.

@GAlexIHU
GAlexIHU requested a review from a team as a code owner April 29, 2026 10:17
@GAlexIHU GAlexIHU added the release-note/bug-fix Release note: Bug Fixes label Apr 29, 2026
@coderabbitai

coderabbitai Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR fixes a recurrence handling bug in the credit engine where recurring grants had their balance resets reapplied unintentionally in later phases. The fix clears the recurredGrants list immediately after processing, preventing duplicate reapplication.

Changes

Cohort / File(s) Summary
Recurrence Balance Reset Fix
openmeter/credit/engine/run.go, openmeter/credit/engine/run_test.go
Production change clears recurredGrants list after applying recurrence balance resets to prevent unintended reapplication in subsequent phases. Test case validates the fix by checking balances after activity changes occur on recurring grants.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

🚥 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 directly describes the main fix: preventing recurring grants from being incorrectly reapplied during in-period activity changes, which matches the core change in the code.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/entitlement-recurrence-balance

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 and usage tips.

@GAlexIHU
GAlexIHU merged commit 253cc22 into main Apr 29, 2026
28 of 30 checks passed
@GAlexIHU
GAlexIHU deleted the fix/entitlement-recurrence-balance branch April 29, 2026 10:39

This branch was previously deployed

1 inactive deployment
dev — 6a6fbfd8 Deployed Apr 29, 2026 by GAlexIHU via Migration Checks #13929
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants