Repository navigation
feat(credits): add feature filters to ledger credits - #4481
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (10)
🚧 Files skipped from review as they are similar to previous changes (8)
📝 WalkthroughWalkthroughAdds 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. ChangesFeature-scoped credit and ledger system
Estimated code review effort 🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
17b6ba2 to
e2d4f4c
Compare
There was a problem hiding this comment.
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 winCollect all validation failures in
Intent.Validate()(don’t early-return onEffectiveAt).Right now
EffectiveAtreturns immediately, so callers won’t get the full set of validation issues from this method. Appending that error toerrskeeps 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() errormethods in Go, collect all validation issues intovar errs []errorand returnmodels.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 liftApply 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 UPDATElock 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 winPlease 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 returnmodels.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() errormethods in Go, collect all validation issues intovar errs []errorand returnmodels.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 winFeature-scoped funding assertion is still checking aggregated FBO balance.
Now that
CreatePromotionalCreditFundingInputsupportsFeatureFilters, 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 winInline 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 winUse a set for feature-filter membership checks.
Nice addition overall. One small optimization: the current
lo.Containscall 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 winAdd 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(Featurespresent 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
⛔ Files ignored due to path filters (14)
openmeter/ent/db/chargecreditpurchase.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase/chargecreditpurchase.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase_update.gois excluded by!**/ent/db/**openmeter/ent/db/creditrealizationlineage.gois excluded by!**/ent/db/**openmeter/ent/db/creditrealizationlineage/creditrealizationlineage.gois excluded by!**/ent/db/**openmeter/ent/db/creditrealizationlineage/where.gois excluded by!**/ent/db/**openmeter/ent/db/creditrealizationlineage_create.gois excluded by!**/ent/db/**openmeter/ent/db/creditrealizationlineage_update.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**openmeter/ent/db/runtime.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (60)
api/v3/handlers/customers/credits/convert.goopenmeter/billing/charges/creditpurchase/adapter/charge.goopenmeter/billing/charges/creditpurchase/adapter/mapper.goopenmeter/billing/charges/creditpurchase/charge.goopenmeter/billing/charges/creditpurchase/charge_test.goopenmeter/billing/charges/creditpurchase/featurefilters.goopenmeter/billing/charges/creditpurchase/service/external.goopenmeter/billing/charges/creditpurchase/service/invoice.goopenmeter/billing/charges/creditpurchase/service/promotional.goopenmeter/billing/charges/flatfee/service/realizations/service.goopenmeter/billing/charges/lineage/adapter/lineage.goopenmeter/billing/charges/lineage/lineage.goopenmeter/billing/charges/lineage/lineage_test.goopenmeter/billing/charges/lineage/service.goopenmeter/billing/charges/lineage/service/service.goopenmeter/billing/charges/models/creditrealization/lineage_specs.goopenmeter/billing/charges/service/lineage_test.goopenmeter/billing/charges/usagebased/service/run/credits.goopenmeter/billing/creditgrant/errors.goopenmeter/billing/creditgrant/service.goopenmeter/billing/creditgrant/service/service.goopenmeter/ent/schema/chargescreditpurchase.goopenmeter/ent/schema/creditrealizationlineage.goopenmeter/ledger/account/adapter/subaccount.goopenmeter/ledger/accounts.goopenmeter/ledger/breakage/service.goopenmeter/ledger/chargeadapter/creditpurchase.goopenmeter/ledger/chargeadapter/creditpurchase_test.goopenmeter/ledger/chargeadapter/flatfee.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/usagebased.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/collector/collect.goopenmeter/ledger/collector/collection_fbo.goopenmeter/ledger/collector/collection_fbo_test.goopenmeter/ledger/collector/correct.goopenmeter/ledger/collector/correct_test.goopenmeter/ledger/collector/service.goopenmeter/ledger/historical/adapter/ledger_test.goopenmeter/ledger/historical/adapter/sumentries_query.goopenmeter/ledger/impact.goopenmeter/ledger/impact_test.goopenmeter/ledger/primitives.goopenmeter/ledger/query.goopenmeter/ledger/routing.goopenmeter/ledger/routing_test.goopenmeter/ledger/routingrules/defaults.goopenmeter/ledger/routingrules/routingrules.goopenmeter/ledger/routingrules/routingrules_test.goopenmeter/ledger/transactions/accrual.goopenmeter/ledger/transactions/customer.gopkg/slicesx/normalize.gopkg/slicesx/normalize_test.gotest/credits/base.gotest/credits/creditgrant_test.gotest/credits/sanity_test.gotools/migrate/migrations/20260601160313_add_credit_feature_filters.down.sqltools/migrate/migrations/20260601160313_add_credit_feature_filters.up.sqltools/migrate/migrations/20260603141000_add_credit_lineage_advance_features.down.sqltools/migrate/migrations/20260603141000_add_credit_lineage_advance_features.up.sql
| 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...) | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
| 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.
| 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))) | ||
| } |
There was a problem hiding this comment.
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.
| 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.
| apiRequestsCharge, err := res[0].AsUsageBasedCharge() | ||
| s.NoError(err) | ||
| storageCharge, err := res[1].AsUsageBasedCharge() | ||
| s.NoError(err) |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
| 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
| 20260601160313_add_credit_feature_filters.up.sql h1:DmZ47ZlkfHYhhF/z7zNGtmFvBFpG0aQ7SuR66ImEcNo= | ||
| 20260603141000_add_credit_lineage_advance_features.up.sql h1:bzApRhx4a6Y3Sixrl6AO2I+qXz0+Aab6SSFWrhx6rS0= |
There was a problem hiding this comment.
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; | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
Summary
Summary by CodeRabbit
New Features
Behavior Changes
Documentation
Tests / Migrations