Skip to content

feat(credits): add feature filters to ledger credits - #4481

Merged
GAlexIHU merged 5 commits into
mainfrom
codex/ledger-credit-feature-filters
Jun 5, 2026
Merged

GAlexIHU merged 5 commits into
mainfrom
codex/ledger-credit-feature-filters

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • add feature filters to credit purchases and carry them through ledger routing, collection, correction, and lineage
  • persist feature filters and advance lineage feature dimensions with generated Ent code and migrations
  • ❗ add a temporary create-time restriction for feature-filtered credit grants until customer balance semantics are defined

Summary by CodeRabbit

  • New Features

    • Enabled feature-filtered credits: restrict credits to specific metered features and route them to matching billing sub-accounts.
    • Collection, advance backfill and settlement flows now respect feature restrictions during allocation and routing.
  • Behavior Changes

    • Creation of credit grants with feature filters is currently rejected (validation error) until balance semantics are defined.
  • Documentation

    • Clarified guidance for Postgres text[] array handling.
  • Tests / Migrations

    • Added extensive tests and DB migrations to support feature filters.

@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f942ce65-97e0-4780-bd02-921ad91afc30

📥 Commits

Reviewing files that changed from the base of the PR and between fe8d76f and 2b1ee3a.

📒 Files selected for processing (10)
  • api/v3/handlers/customers/credits/convert.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/creditpurchase/charge_test.go
  • openmeter/billing/charges/creditpurchase/featurefilters.go
  • openmeter/billing/charges/creditpurchase/service/external.go
  • openmeter/billing/charges/creditpurchase/service/invoice.go
  • openmeter/billing/charges/creditpurchase/service/promotional.go
  • openmeter/billing/charges/service/lineage_test.go
  • openmeter/ledger/chargeadapter/creditpurchase.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
🚧 Files skipped from review as they are similar to previous changes (8)
  • openmeter/billing/charges/creditpurchase/service/invoice.go
  • openmeter/billing/charges/creditpurchase/service/external.go
  • openmeter/billing/charges/creditpurchase/charge_test.go
  • api/v3/handlers/customers/credits/convert.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
  • openmeter/billing/charges/service/lineage_test.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/ledger/chargeadapter/creditpurchase.go

📝 Walkthrough

Walkthrough

Adds feature-filter support for purchased/promotional credits and propagates a feature dimension through lineage, ledger routing, collector selection, advance attribution, correction reissue, API conversion, schemas, migrations, and tests.

Changes

Feature-scoped credit and ledger system

Layer / File(s) Summary
Feature filter primitives and credit purchase intent
pkg/slicesx/normalize.go, openmeter/billing/charges/creditpurchase/featurefilters.go, openmeter/billing/charges/creditpurchase/charge.go, openmeter/billing/charges/creditpurchase/adapter/mapper.go, openmeter/ent/schema/chargescreditpurchase.go, tools/migrate/migrations/20260605120000_add_credit_feature_filters.up.sql
Introduce FeatureFilters type with Normalize/Validate, add slices utility, persist feature filters to DB text[] column, and map intent ↔ DB.
Credit grant API conversion and validation guard
api/v3/handlers/customers/credits/convert.go, openmeter/billing/creditgrant/errors.go, openmeter/billing/creditgrant/service.go, openmeter/billing/creditgrant/service/service.go
Add API converters for grant filters; parse and validate grant Filters on create and temporarily reject non-empty feature filters with a specific validation error code.
Advance lineage feature storage and backfill filtering
openmeter/billing/charges/lineage/lineage.go, openmeter/billing/charges/lineage/service.go, openmeter/billing/charges/lineage/adapter/lineage.go, openmeter/billing/charges/lineage/service/service.go, openmeter/billing/charges/service/lineage_test.go, openmeter/billing/charges/usagebased/service/run/credits.go, openmeter/billing/charges/flatfee/service/realizations/service.go
Persist advance features on lineage records, add matching/filtering helpers, pass FeatureFilters into backfill calls, and test backfill filtering by advance features.
Route feature semantics and matching
openmeter/ledger/primitives.go, openmeter/ledger/routing.go, openmeter/ledger/routing_test.go, openmeter/ledger/query.go, openmeter/ledger/impact.go, openmeter/ledger/historical/adapter/sumentries_query.go, openmeter/ledger/historical/adapter/ledger_test.go
Make RouteFilter.Features an optional field, validate/normalize feature sets, implement order-insensitive equality matching, and update ledger queries/tests to use tri-state feature logic.
Route params and transaction templates carry features
openmeter/ledger/accounts.go, openmeter/ledger/breakage/service.go, openmeter/ledger/transactions/customer.go, openmeter/ledger/transactions/accrual.go
Thread Features through route params and transaction templates (issuance/authorize/settle/transfer), and support Advance vs Attributed features for cost-basis attribution.
Routing rule scope for feature dimension
openmeter/ledger/routingrules/defaults.go, openmeter/ledger/routingrules/routingrules.go, openmeter/ledger/routingrules/routingrules_test.go
New validator RequireFeatureDimensionScopeRule restricts features to FBO/receivable accounts; authorization-stage matching no longer requires feature equality.
Collector feature-aware FBO source selection
openmeter/ledger/collector/service.go, openmeter/ledger/collector/collect.go, openmeter/ledger/collector/collection_fbo.go, openmeter/ledger/collector/collection_fbo_test.go
Collector gains FeatureKey input, filters FBO sources by feature eligibility (applying priority before feature restriction), marks feature-restricted sources, and adds integration tests/helpers.
Charge adapter propagation and advance attribution filtering
openmeter/ledger/chargeadapter/flatfee.go, openmeter/ledger/chargeadapter/usagebased.go, openmeter/ledger/chargeadapter/creditpurchase.go, openmeter/ledger/chargeadapter/*_test.go
Propagate feature keys/filters into collector inputs and ledger templates; filter advance attributions using lineage FeatureFiltersMatchAdvance; update adapters and tests for feature-aware routing.
Feature-aware correction and backfilled credit reissue
openmeter/ledger/collector/correct.go, openmeter/ledger/collector/correct_test.go
Introduce merge-key for planned corrections and thread features through reissued backfilled credits; add integration tests validating feature-aware correction behavior and breakage reopen semantics.
Credits test scaffolding and sanity flows
test/credits/base.go, test/credits/creditgrant_test.go, test/credits/sanity_test.go
Extend test helpers and intents to support FeatureFilters and feature-key charges; add feature-restricted correction/backfill sanity tests and helpers for meter/feature setup.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • openmeterio/openmeter#4457: Related changes around grantPromotionalCredit and promotional credit flows where FeatureFilters are now threaded.
  • openmeterio/openmeter#4158: Modifies grant API conversion in the same api/v3/handlers/customers/credits/convert.go area where this PR adds feature-filter mapping.
  • openmeterio/openmeter#4236: Overlaps at credit-purchase payment/template dispatch sites where this PR propagates feature dimensions into templates.

Suggested reviewers

  • tothandras
✨ 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 codex/ledger-credit-feature-filters

@GAlexIHU GAlexIHU added the release-note/ignore Ignore this change when generating release notes label Jun 4, 2026
@GAlexIHU
GAlexIHU force-pushed the codex/ledger-credit-feature-filters branch from 17b6ba2 to e2d4f4c Compare June 4, 2026 12:56
@GAlexIHU
GAlexIHU marked this pull request as ready for review June 4, 2026 12:57
@GAlexIHU
GAlexIHU requested a review from a team as a code owner June 4, 2026 12:57

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
openmeter/billing/charges/creditpurchase/charge.go (1)

152-196: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Collect all validation failures in Intent.Validate() (don’t early-return on EffectiveAt).

Right now EffectiveAt returns immediately, so callers won’t get the full set of validation issues from this method. Appending that error to errs keeps behavior consistent with the rest of the validator.

Suggested fix
 	if i.EffectiveAt != nil {
-		return errors.New("effective at is not yet supported")
+		errs = append(errs, errors.New("effective at is not yet supported"))
 	}

As per coding guidelines: "For Validate() error methods in Go, collect all validation issues into var errs []error and return models.NewNillableGenericValidationError(errors.Join(errs...)) instead of returning on the first invalid field".

🤖 Prompt for 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.

In `@openmeter/billing/charges/creditpurchase/charge.go` around lines 152 - 196,
The Intent.Validate() method currently returns early when i.EffectiveAt != nil
which prevents collecting other validation failures; instead of returning
errors.New("effective at is not yet supported") inside Intent.Validate(), append
that error to the errs slice (e.g., errs = append(errs, fmt.Errorf("effective at
is not yet supported"))) so it is included in the aggregated errors returned by
models.NewNillableGenericValidationError(errors.Join(errs...)); keep the
existing ExpiresAt check that compares i.ExpiresAt with i.CalculateEffectiveAt()
and ensure the final return still uses
models.NewNillableGenericValidationError(errors.Join(errs...)).
openmeter/billing/charges/lineage/service/service.go (1)

184-194: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Apply feature filtering before taking row locks.

Right now the flow locks all uncovered advance lineages for the customer/currency, and only then filters by feature in memory. That broadens FOR UPDATE lock scope and can create avoidable contention for unrelated feature dimensions.

Please push feature-filter matching into the adapter lock query so only eligible lineages are locked.

As per coding guidelines: “Performance should be a priority in critical code paths. Anything related to ... database operations ... should be vetted for potential performance bottlenecks”.

🤖 Prompt for 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.

In `@openmeter/billing/charges/lineage/service/service.go` around lines 184 - 194,
The current flow calls s.adapter.LockAdvanceLineagesForBackfill(...) to acquire
FOR UPDATE locks then applies lineage.FilterAdvanceLineagesForBackfill(...) in
memory, widening lock scope; change the adapter API and call site so feature
filters are applied inside the locking query: add feature filter parameters
(e.g. pass input.FeatureFilters) to LockAdvanceLineagesForBackfill and implement
the filter in the adapter SQL/ORM WHERE clause that performs the FOR UPDATE
locking, then remove the subsequent in-memory call to
lineage.FilterAdvanceLineagesForBackfill in service.go and ensure the adapter
still returns an empty slice when no rows match (including when filters are
nil/empty to preserve behavior).
openmeter/ledger/routing.go (1)

173-206: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Please align Route.Validate() with the repo validation error contract.

Nice addition with validateFeatures, but this method still exits on first error and returns raw errors. Can we aggregate all field validation failures and return models.NewNillableGenericValidationError(errors.Join(errs...)) for consistency with the Go validation pattern used in this repo?

Proposed patch
 func (r Route) Validate() error {
-	if err := ValidateCurrency(r.Currency); err != nil {
-		return err
-	}
+	var errs []error
 
+	if err := ValidateCurrency(r.Currency); err != nil {
+		errs = append(errs, err)
+	}
 	if r.CreditPriority != nil {
 		if err := ValidateCreditPriority(*r.CreditPriority); err != nil {
-			return err
+			errs = append(errs, err)
 		}
 	}
-
 	if r.CostBasis != nil {
 		if err := ValidateCostBasis(*r.CostBasis); err != nil {
-			return err
+			errs = append(errs, err)
 		}
 	}
-
 	if r.TransactionAuthorizationStatus != nil {
 		if err := r.TransactionAuthorizationStatus.Validate(); err != nil {
-			return err
+			errs = append(errs, err)
 		}
 	}
-
 	if r.TaxBehavior != nil {
 		if err := r.TaxBehavior.Validate(); err != nil {
-			return err
+			errs = append(errs, err)
 		}
 	}
-
 	if err := validateFeatures(r.Features); err != nil {
-		return fmt.Errorf("features: %w", err)
+		errs = append(errs, fmt.Errorf("features: %w", err))
 	}
-
-	return nil
+	return models.NewNillableGenericValidationError(errors.Join(errs...))
 }

As per coding guidelines: “For Validate() error methods in Go, collect all validation issues into var errs []error and return models.NewNillableGenericValidationError(errors.Join(errs...)) instead of returning on the first invalid field.”

🤖 Prompt for 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.

In `@openmeter/ledger/routing.go` around lines 173 - 206, Route.Validate currently
returns on the first validation error and returns raw errors; change it to
collect all failures into a slice (e.g., var errs []error), append errors from
ValidateCurrency, ValidateCreditPriority, ValidateCostBasis,
TransactionAuthorizationStatus.Validate, TaxBehavior.Validate and
validateFeatures (wrap validateFeatures error with context like "features: %w"),
then if len(errs)>0 return
models.NewNillableGenericValidationError(errors.Join(errs...)) else return nil;
use the existing function name Route.Validate and the symbols validateFeatures,
models.NewNillableGenericValidationError and errors.Join to locate where to
aggregate errors.
test/credits/base.go (1)

684-697: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Feature-scoped funding assertion is still checking aggregated FBO balance.

Now that CreatePromotionalCreditFundingInput supports FeatureFilters, this assertion path can validate the wrong bucket when multiple feature-scoped balances share the same priority/cost-basis. Please switch these checks to the feature-aware helper (MustCustomerFBOBalanceWithPriorityForFeatures / MustCustomerFBOBalanceForFeatures) using the same feature set passed into the created intent.

🤖 Prompt for 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.

In `@test/credits/base.go` around lines 684 - 697, The test is asserting
aggregated FBO balances but must target feature-scoped buckets now that
CreatePromotionalCreditFundingInput supports FeatureFilters; update the branch
that currently calls
MustCustomerFBOBalanceWithPriority/AsOf/WithPriorityAsOf/MustCustomerFBOBalance/MustCustomerFBOBalanceAsOf
to instead call the feature-aware variants
MustCustomerFBOBalanceWithPriorityForFeatures (when input.Priority is present)
and MustCustomerFBOBalanceForFeatures (when no Priority) and pass the same
feature set from the created intent (the FeatureFilters from
CreatePromotionalCreditFundingInput) along with the existing parameters and the
expiresAt/AsOf handling so each branch mirrors the original logic but scopes
checks to the feature filters.
🧹 Nitpick comments (3)
openmeter/billing/charges/usagebased/service/run/credits.go (1)

28-50: ⚡ Quick win

Inline this single-use feature slice guard instead of keeping a helper.

This helper is only called once and only wraps a tiny guard, so keeping it inline will match the repo’s Go style and keep flow easier to scan.

Suggested refactor
 func (s *Service) createRunCreditRealizations(ctx context.Context, charge usagebased.Charge, runID usagebased.RealizationRunID, creditAllocations creditrealization.CreateInputs) (creditrealization.Realizations, error) {
 	realizations, err := s.adapter.CreateRunCreditRealization(ctx, runID, creditAllocations)
 	if err != nil {
 		return nil, err
 	}
 
+	var features []string
+	if charge.Intent.FeatureKey != "" {
+		features = []string{charge.Intent.FeatureKey}
+	}
+
 	if err := s.lineage.CreateInitialLineages(ctx, lineage.CreateInitialLineagesInput{
 		Namespace:    charge.Namespace,
 		ChargeID:     charge.ID,
 		CustomerID:   charge.Intent.CustomerID,
 		Currency:     charge.Intent.Currency,
-		Features:     featuresForLineage(charge.Intent.FeatureKey),
+		Features:     features,
 		Realizations: realizations,
 	}); err != nil {
 		return nil, fmt.Errorf("create initial credit realization lineages: %w", err)
 	}
@@
 	return realizations, nil
 }
-
-func featuresForLineage(featureKey string) []string {
-	if featureKey == "" {
-		return nil
-	}
-
-	return []string{featureKey}
-}

As per coding guidelines: **/*.go: Do not extract helper functions only to hide a couple of simple operations or short guard checks; keep code inline unless the name adds meaningful domain or business intent.

🤖 Prompt for 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.

In `@openmeter/billing/charges/usagebased/service/run/credits.go` around lines 28
- 50, The small helper featuresForLineage is single-use and should be inlined:
replace the call sites (e.g., where Features:
featuresForLineage(charge.Intent.FeatureKey) is set when creating the initial
credit realization lineages) with an inline guard expression that yields nil
when charge.Intent.FeatureKey == "" or []string{charge.Intent.FeatureKey}
otherwise, then remove the featuresForLineage function declaration entirely;
ensure any imports/usages still compile after removing the function.
openmeter/billing/charges/lineage/lineage.go (1)

62-64: ⚡ Quick win

Use a set for feature-filter membership checks.

Nice addition overall. One small optimization: the current lo.Contains call inside the loop does repeated linear scans. Building a set once will keep this path cheaper when either slice grows.

♻️ Suggested refactor
 func FeatureFiltersMatchAdvance(featureFilters []string, advanceFeatures []string) bool {
 	if len(featureFilters) == 0 {
 		return true
 	}

 	if len(advanceFeatures) == 0 {
 		return false
 	}

+	filterSet := make(map[string]struct{}, len(featureFilters))
+	for _, feature := range featureFilters {
+		filterSet[feature] = struct{}{}
+	}
+
 	for _, feature := range advanceFeatures {
-		if lo.Contains(featureFilters, feature) {
+		if _, ok := filterSet[feature]; ok {
 			return true
 		}
 	}

 	return false
 }

As per coding guidelines: “Performance should be a priority in critical code paths. Anything related to ... database operations ... should be vetted for potential performance bottlenecks”.

🤖 Prompt for 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.

In `@openmeter/billing/charges/lineage/lineage.go` around lines 62 - 64, The loop
over advanceFeatures currently calls lo.Contains(featureFilters, feature) on
every iteration causing repeated linear scans; before iterating (in the same
function where advanceFeatures and featureFilters are used) build a membership
set from featureFilters (e.g., map[string]struct{} keyed by the filter values)
and then replace the lo.Contains call with a constant-time map lookup (check
presence in that map) so the loop uses O(1) membership checks instead of
repeated O(n) scans.
openmeter/ledger/historical/adapter/ledger_test.go (1)

972-994: ⚡ Quick win

Add one assertion for the empty-present features path.

Nice coverage for canonical non-empty matching. One small gap: the new branch at Line 140 in openmeter/ledger/historical/adapter/sumentries_query.go (Features present but empty) isn’t exercised yet, so regressions there could slip through.

Suggested test addition
 	sumPartialFeatures, err := env.repo.SumEntries(ctx, ledger.Query{
 		Namespace: namespace,
 		Filters: ledger.Filters{
 			Route: ledger.RouteFilter{
 				Currency: currencyx.Code("USD"),
 				Features: mo.Some([]string{"api-calls"}),
 			},
 		},
 	})
 	require.NoError(t, err)
 	require.True(t, sumPartialFeatures.Equal(alpacadecimal.Zero))
+
+	sumEmptyFeatures, err := env.repo.SumEntries(ctx, ledger.Query{
+		Namespace: namespace,
+		Filters: ledger.Filters{
+			Route: ledger.RouteFilter{
+				Currency: currencyx.Code("USD"),
+				Features: mo.Some([]string{}),
+			},
+		},
+	})
+	require.NoError(t, err)
+	require.True(t, sumEmptyFeatures.Equal(alpacadecimal.NewFromInt(35)))

As per coding guidelines, **/*_test.go: “Make sure the tests are comprehensive and cover the changes.”

🤖 Prompt for 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.

In `@openmeter/ledger/historical/adapter/ledger_test.go` around lines 972 - 994,
Add a test that exercises the "Features present but empty" branch by calling
env.repo.SumEntries with ledger.Query/ledger.Filters/ledger.RouteFilter where
RouteFilter.Features is set to mo.Some([]string{}) (an explicitly present empty
slice) and assert the returned sum equals alpacadecimal.Zero; place this after
the existing sumPartialFeatures block to cover the new branch in
sumentries_query.go and use require.NoError and
require.True(sum.Equal(alpacadecimal.Zero)) as in the other assertions.
🤖 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 `@openmeter/ledger/collector/service.go`:
- Around line 38-61: Replace the direct return of errors.Join in Config.Validate
with the standard nillable validation wrapper: collect errs as done, then return
models.NewNillableGenericValidationError(errors.Join(errs...)) instead of return
errors.Join(errs...), so callers receive the expected nillable validation error;
update the return statement in the Config.Validate function accordingly and
ensure models is imported/available.

In `@pkg/slicesx/normalize_test.go`:
- Around line 9-13: Add assertions in TestNormalize to ensure the input slices
passed to Normalize are not mutated: for each case (the string slice
{"storage","api-calls","storage"} and the int slice {3,1,2,1}) capture a copy of
the original input (or store the expected original literal) before calling
Normalize and assert the original input equals that copy after the call; also
assert that passing a nil slice remains nil. This ensures Normalize (used in
TestNormalize) does not mutate its input.

In `@test/credits/sanity_test.go`:
- Around line 1811-1814: The test assumes ordering of res by assigning
res[0]/res[1] to apiRequestsCharge/storageCharge; instead iterate over res, call
AsUsageBasedCharge() for each item and inspect a stable identifier (e.g.,
metric/name/product/charge type field) to assign the right variable—e.g., for
each charge := res[i].AsUsageBasedCharge() if charge.MetricName ==
"api_requests" set apiRequestsCharge = charge else if charge.MetricName ==
"storage" set storageCharge = charge; assert both were found and no errors. Use
the actual identifier field present on the returned object (replace MetricName
with the real property if different) so the test no longer depends on
create-result order.

---

Outside diff comments:
In `@openmeter/billing/charges/creditpurchase/charge.go`:
- Around line 152-196: The Intent.Validate() method currently returns early when
i.EffectiveAt != nil which prevents collecting other validation failures;
instead of returning errors.New("effective at is not yet supported") inside
Intent.Validate(), append that error to the errs slice (e.g., errs =
append(errs, fmt.Errorf("effective at is not yet supported"))) so it is included
in the aggregated errors returned by
models.NewNillableGenericValidationError(errors.Join(errs...)); keep the
existing ExpiresAt check that compares i.ExpiresAt with i.CalculateEffectiveAt()
and ensure the final return still uses
models.NewNillableGenericValidationError(errors.Join(errs...)).

In `@openmeter/billing/charges/lineage/service/service.go`:
- Around line 184-194: The current flow calls
s.adapter.LockAdvanceLineagesForBackfill(...) to acquire FOR UPDATE locks then
applies lineage.FilterAdvanceLineagesForBackfill(...) in memory, widening lock
scope; change the adapter API and call site so feature filters are applied
inside the locking query: add feature filter parameters (e.g. pass
input.FeatureFilters) to LockAdvanceLineagesForBackfill and implement the filter
in the adapter SQL/ORM WHERE clause that performs the FOR UPDATE locking, then
remove the subsequent in-memory call to lineage.FilterAdvanceLineagesForBackfill
in service.go and ensure the adapter still returns an empty slice when no rows
match (including when filters are nil/empty to preserve behavior).

In `@openmeter/ledger/routing.go`:
- Around line 173-206: Route.Validate currently returns on the first validation
error and returns raw errors; change it to collect all failures into a slice
(e.g., var errs []error), append errors from ValidateCurrency,
ValidateCreditPriority, ValidateCostBasis,
TransactionAuthorizationStatus.Validate, TaxBehavior.Validate and
validateFeatures (wrap validateFeatures error with context like "features: %w"),
then if len(errs)>0 return
models.NewNillableGenericValidationError(errors.Join(errs...)) else return nil;
use the existing function name Route.Validate and the symbols validateFeatures,
models.NewNillableGenericValidationError and errors.Join to locate where to
aggregate errors.

In `@test/credits/base.go`:
- Around line 684-697: The test is asserting aggregated FBO balances but must
target feature-scoped buckets now that CreatePromotionalCreditFundingInput
supports FeatureFilters; update the branch that currently calls
MustCustomerFBOBalanceWithPriority/AsOf/WithPriorityAsOf/MustCustomerFBOBalance/MustCustomerFBOBalanceAsOf
to instead call the feature-aware variants
MustCustomerFBOBalanceWithPriorityForFeatures (when input.Priority is present)
and MustCustomerFBOBalanceForFeatures (when no Priority) and pass the same
feature set from the created intent (the FeatureFilters from
CreatePromotionalCreditFundingInput) along with the existing parameters and the
expiresAt/AsOf handling so each branch mirrors the original logic but scopes
checks to the feature filters.

---

Nitpick comments:
In `@openmeter/billing/charges/lineage/lineage.go`:
- Around line 62-64: The loop over advanceFeatures currently calls
lo.Contains(featureFilters, feature) on every iteration causing repeated linear
scans; before iterating (in the same function where advanceFeatures and
featureFilters are used) build a membership set from featureFilters (e.g.,
map[string]struct{} keyed by the filter values) and then replace the lo.Contains
call with a constant-time map lookup (check presence in that map) so the loop
uses O(1) membership checks instead of repeated O(n) scans.

In `@openmeter/billing/charges/usagebased/service/run/credits.go`:
- Around line 28-50: The small helper featuresForLineage is single-use and
should be inlined: replace the call sites (e.g., where Features:
featuresForLineage(charge.Intent.FeatureKey) is set when creating the initial
credit realization lineages) with an inline guard expression that yields nil
when charge.Intent.FeatureKey == "" or []string{charge.Intent.FeatureKey}
otherwise, then remove the featuresForLineage function declaration entirely;
ensure any imports/usages still compile after removing the function.

In `@openmeter/ledger/historical/adapter/ledger_test.go`:
- Around line 972-994: Add a test that exercises the "Features present but
empty" branch by calling env.repo.SumEntries with
ledger.Query/ledger.Filters/ledger.RouteFilter where RouteFilter.Features is set
to mo.Some([]string{}) (an explicitly present empty slice) and assert the
returned sum equals alpacadecimal.Zero; place this after the existing
sumPartialFeatures block to cover the new branch in sumentries_query.go and use
require.NoError and require.True(sum.Equal(alpacadecimal.Zero)) as in the other
assertions.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0b4dd5f1-6807-451e-849b-2ed5a17201e0

📥 Commits

Reviewing files that changed from the base of the PR and between 8e5f04d and e2d4f4c.

⛔ Files ignored due to path filters (14)
  • openmeter/ent/db/chargecreditpurchase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase/chargecreditpurchase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/creditrealizationlineage.go is excluded by !**/ent/db/**
  • openmeter/ent/db/creditrealizationlineage/creditrealizationlineage.go is excluded by !**/ent/db/**
  • openmeter/ent/db/creditrealizationlineage/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/creditrealizationlineage_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/creditrealizationlineage_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (60)
  • api/v3/handlers/customers/credits/convert.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper.go
  • openmeter/billing/charges/creditpurchase/charge.go
  • openmeter/billing/charges/creditpurchase/charge_test.go
  • openmeter/billing/charges/creditpurchase/featurefilters.go
  • openmeter/billing/charges/creditpurchase/service/external.go
  • openmeter/billing/charges/creditpurchase/service/invoice.go
  • openmeter/billing/charges/creditpurchase/service/promotional.go
  • openmeter/billing/charges/flatfee/service/realizations/service.go
  • openmeter/billing/charges/lineage/adapter/lineage.go
  • openmeter/billing/charges/lineage/lineage.go
  • openmeter/billing/charges/lineage/lineage_test.go
  • openmeter/billing/charges/lineage/service.go
  • openmeter/billing/charges/lineage/service/service.go
  • openmeter/billing/charges/models/creditrealization/lineage_specs.go
  • openmeter/billing/charges/service/lineage_test.go
  • openmeter/billing/charges/usagebased/service/run/credits.go
  • openmeter/billing/creditgrant/errors.go
  • openmeter/billing/creditgrant/service.go
  • openmeter/billing/creditgrant/service/service.go
  • openmeter/ent/schema/chargescreditpurchase.go
  • openmeter/ent/schema/creditrealizationlineage.go
  • openmeter/ledger/account/adapter/subaccount.go
  • openmeter/ledger/accounts.go
  • openmeter/ledger/breakage/service.go
  • openmeter/ledger/chargeadapter/creditpurchase.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
  • openmeter/ledger/chargeadapter/flatfee.go
  • openmeter/ledger/chargeadapter/flatfee_test.go
  • openmeter/ledger/chargeadapter/usagebased.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
  • openmeter/ledger/collector/collect.go
  • openmeter/ledger/collector/collection_fbo.go
  • openmeter/ledger/collector/collection_fbo_test.go
  • openmeter/ledger/collector/correct.go
  • openmeter/ledger/collector/correct_test.go
  • openmeter/ledger/collector/service.go
  • openmeter/ledger/historical/adapter/ledger_test.go
  • openmeter/ledger/historical/adapter/sumentries_query.go
  • openmeter/ledger/impact.go
  • openmeter/ledger/impact_test.go
  • openmeter/ledger/primitives.go
  • openmeter/ledger/query.go
  • openmeter/ledger/routing.go
  • openmeter/ledger/routing_test.go
  • openmeter/ledger/routingrules/defaults.go
  • openmeter/ledger/routingrules/routingrules.go
  • openmeter/ledger/routingrules/routingrules_test.go
  • openmeter/ledger/transactions/accrual.go
  • openmeter/ledger/transactions/customer.go
  • pkg/slicesx/normalize.go
  • pkg/slicesx/normalize_test.go
  • test/credits/base.go
  • test/credits/creditgrant_test.go
  • test/credits/sanity_test.go
  • tools/migrate/migrations/20260601160313_add_credit_feature_filters.down.sql
  • tools/migrate/migrations/20260601160313_add_credit_feature_filters.up.sql
  • tools/migrate/migrations/20260603141000_add_credit_lineage_advance_features.down.sql
  • tools/migrate/migrations/20260603141000_add_credit_lineage_advance_features.up.sql

Comment on lines +38 to +61
func (c Config) Validate() error {
var errs []error

if c.Ledger == nil {
errs = append(errs, fmt.Errorf("ledger is required"))
}
if c.Dependencies.AccountService == nil {
errs = append(errs, fmt.Errorf("account service is required"))
}
if c.Dependencies.AccountCatalog == nil {
errs = append(errs, fmt.Errorf("account catalog is required"))
}
if c.Dependencies.BalanceQuerier == nil {
errs = append(errs, fmt.Errorf("balance querier is required"))
}
if c.AccountLocker == nil {
errs = append(errs, fmt.Errorf("account locker is required"))
}
if c.TransactionManager == nil {
errs = append(errs, fmt.Errorf("transaction manager is required"))
}

return errors.Join(errs...)
}

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.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Config.Validate() should return the standard nillable validation error wrapper.

Great call adding aggregated validation here. One small contract mismatch: this should return models.NewNillableGenericValidationError(errors.Join(errs...)) instead of returning errors.Join directly.

Proposed patch
 func (c Config) Validate() error {
 	var errs []error
@@
-	return errors.Join(errs...)
+	return models.NewNillableGenericValidationError(errors.Join(errs...))
 }

As per coding guidelines: “For Validate() error methods in Go, collect all validation issues into var errs []error and return models.NewNillableGenericValidationError(errors.Join(errs...)) instead of returning on the first invalid field.”

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (c Config) Validate() error {
var errs []error
if c.Ledger == nil {
errs = append(errs, fmt.Errorf("ledger is required"))
}
if c.Dependencies.AccountService == nil {
errs = append(errs, fmt.Errorf("account service is required"))
}
if c.Dependencies.AccountCatalog == nil {
errs = append(errs, fmt.Errorf("account catalog is required"))
}
if c.Dependencies.BalanceQuerier == nil {
errs = append(errs, fmt.Errorf("balance querier is required"))
}
if c.AccountLocker == nil {
errs = append(errs, fmt.Errorf("account locker is required"))
}
if c.TransactionManager == nil {
errs = append(errs, fmt.Errorf("transaction manager is required"))
}
return errors.Join(errs...)
}
func (c Config) Validate() error {
var errs []error
if c.Ledger == nil {
errs = append(errs, fmt.Errorf("ledger is required"))
}
if c.Dependencies.AccountService == nil {
errs = append(errs, fmt.Errorf("account service is required"))
}
if c.Dependencies.AccountCatalog == nil {
errs = append(errs, fmt.Errorf("account catalog is required"))
}
if c.Dependencies.BalanceQuerier == nil {
errs = append(errs, fmt.Errorf("balance querier is required"))
}
if c.AccountLocker == nil {
errs = append(errs, fmt.Errorf("account locker is required"))
}
if c.TransactionManager == nil {
errs = append(errs, fmt.Errorf("transaction manager is required"))
}
return models.NewNillableGenericValidationError(errors.Join(errs...))
}
🤖 Prompt for 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.

In `@openmeter/ledger/collector/service.go` around lines 38 - 61, Replace the
direct return of errors.Join in Config.Validate with the standard nillable
validation wrapper: collect errs as done, then return
models.NewNillableGenericValidationError(errors.Join(errs...)) instead of return
errors.Join(errs...), so callers receive the expected nillable validation error;
update the return statement in the Config.Validate function accordingly and
ensure models is imported/available.

Comment on lines +9 to +13
func TestNormalize(t *testing.T) {
require.Equal(t, []string{"api-calls", "storage"}, Normalize([]string{"storage", "api-calls", "storage"}))
require.Equal(t, []int{1, 2, 3}, Normalize([]int{3, 1, 2, 1}))
require.Nil(t, Normalize([]string(nil)))
}

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add an input immutability assertion for Normalize.

Nice coverage on ordering/dedup/nil. One important behavior is still untested: the input slice should not be mutated. Without that assertion, a future regression (e.g., removing slices.Clone) won’t be caught.

Suggested test addition
 func TestNormalize(t *testing.T) {
+	in := []string{"storage", "api-calls", "storage"}
+	out := Normalize(in)
+
+	require.Equal(t, []string{"api-calls", "storage"}, out)
+	require.Equal(t, []string{"storage", "api-calls", "storage"}, in)
+
-	require.Equal(t, []string{"api-calls", "storage"}, Normalize([]string{"storage", "api-calls", "storage"}))
 	require.Equal(t, []int{1, 2, 3}, Normalize([]int{3, 1, 2, 1}))
 	require.Nil(t, Normalize([]string(nil)))
 }

As per coding guidelines: **/*_test.go: Make sure the tests are comprehensive and cover the changes.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func TestNormalize(t *testing.T) {
require.Equal(t, []string{"api-calls", "storage"}, Normalize([]string{"storage", "api-calls", "storage"}))
require.Equal(t, []int{1, 2, 3}, Normalize([]int{3, 1, 2, 1}))
require.Nil(t, Normalize([]string(nil)))
}
func TestNormalize(t *testing.T) {
in := []string{"storage", "api-calls", "storage"}
out := Normalize(in)
require.Equal(t, []string{"api-calls", "storage"}, out)
require.Equal(t, []string{"storage", "api-calls", "storage"}, in)
require.Equal(t, []int{1, 2, 3}, Normalize([]int{3, 1, 2, 1}))
require.Nil(t, Normalize([]string(nil)))
}
🤖 Prompt for 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.

In `@pkg/slicesx/normalize_test.go` around lines 9 - 13, Add assertions in
TestNormalize to ensure the input slices passed to Normalize are not mutated:
for each case (the string slice {"storage","api-calls","storage"} and the int
slice {3,1,2,1}) capture a copy of the original input (or store the expected
original literal) before calling Normalize and assert the original input equals
that copy after the call; also assert that passing a nil slice remains nil. This
ensures Normalize (used in TestNormalize) does not mutate its input.

Comment on lines +1811 to +1814
apiRequestsCharge, err := res[0].AsUsageBasedCharge()
s.NoError(err)
storageCharge, err := res[1].AsUsageBasedCharge()
s.NoError(err)

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Avoid relying on multi-intent create result order.

This test assumes res[0] is API-requests and res[1] is storage. If create-result ordering changes, the test can become flaky and patch/assert against the wrong charge IDs.

🤖 Prompt for 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.

In `@test/credits/sanity_test.go` around lines 1811 - 1814, The test assumes
ordering of res by assigning res[0]/res[1] to apiRequestsCharge/storageCharge;
instead iterate over res, call AsUsageBasedCharge() for each item and inspect a
stable identifier (e.g., metric/name/product/charge type field) to assign the
right variable—e.g., for each charge := res[i].AsUsageBasedCharge() if
charge.MetricName == "api_requests" set apiRequestsCharge = charge else if
charge.MetricName == "storage" set storageCharge = charge; assert both were
found and no errors. Use the actual identifier field present on the returned
object (replace MetricName with the real property if different) so the test no
longer depends on create-result order.

ID: charge.Intent.CustomerID,
}
annotations := chargeAnnotationsForCreditPurchaseCharge(charge)
featureFilters := charge.Intent.FeatureFilters.Strings()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
featureFilters := charge.Intent.FeatureFilters.Strings()
featureFilters := charge.Intent.FeatureFilters.Normalize()

I don't like that Strings actually also normalizes. FeatureFilters will be usable as []string input.

Let's drop the Strings() member, as the type itself or .Normalize() output is fully interchangeable with []string

Comment thread tools/migrate/migrations/atlas.sum Outdated
Comment on lines +209 to +210
20260601160313_add_credit_feature_filters.up.sql h1:DmZ47ZlkfHYhhF/z7zNGtmFvBFpG0aQ7SuR66ImEcNo=
20260603141000_add_credit_lineage_advance_features.up.sql h1:bzApRhx4a6Y3Sixrl6AO2I+qXz0+Aab6SSFWrhx6rS0=

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

May I ask you to merge these two pretty please?

@@ -0,0 +1,2 @@
-- modify "credit_realization_lineages" table
ALTER TABLE "credit_realization_lineages" ADD COLUMN "advance_features" jsonb NULL;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I know postgresql []string is a pain, but shouldn't we use that instead? GIN indexes are not composable afaik.

This is more like a question, so I can live with jsonb.

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.

yeah i was also surprised when saw this in the generation but this is the ent default (didnt bother to check how we do elsewhere but i assume we do this) *i did check now, we don't actually use field.Strings() anywhere, updated repo guidance on it... thx for making me check agian 👍

as for GIN: i think btree would do practically nothing on []text, it would only be good for identity checks (&hence sorting) i think you'd need GIN for membership checks either way... but still, lets follow our patterns :D

turip
turip previously approved these changes Jun 5, 2026
@GAlexIHU
GAlexIHU merged commit 6eba832 into main Jun 5, 2026
26 of 27 checks passed
@GAlexIHU
GAlexIHU deleted the codex/ledger-credit-feature-filters branch June 5, 2026 11:57
This was referenced Jun 17, 2026

This branch was previously deployed

1 inactive deployment
dev — 2b1ee3a0 Deployed Jun 5, 2026 by GAlexIHU via Migration Checks #14841
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants