Repository navigation
feat(ledger): revenue recognition - #4230
Conversation
|
Caution Review failedPull request was closed or merged during review 📝 WalkthroughWalkthroughThis PR introduces earnings recognition for credit purchases, wiring a new Changes
Sequence DiagramsequenceDiagram
participant ChargeService as Charge Service
participant Recognizer as Recognizer Service
participant Lineage as Lineage Service
participant Ledger as Ledger
participant TxManager as Transaction Manager
ChargeService->>Recognizer: RecognizeEarnings(customerID, at, currency)
activate Recognizer
Recognizer->>Lineage: LoadLineagesByCustomer(namespace, customerID, currency)
activate Lineage
Lineage-->>Recognizer: [lineages with eligible segments]
deactivate Lineage
Note over Recognizer: Filter segments by state<br/>(RealCredit, AdvanceBackfilled)
Recognizer->>Ledger: ResolveTransactions(template, amount, at)
activate Ledger
Ledger-->>Recognizer: resolved transaction group
deactivate Ledger
Recognizer->>Ledger: CommitGroup(resolved group)
activate Ledger
Ledger-->>Recognizer: ledger group ID
deactivate Ledger
Note over Recognizer: Allocate across eligible<br/>segments deterministically
loop For each eligible segment
Recognizer->>TxManager: CreateSegment(earnings_recognized state, source tracking)
activate TxManager
TxManager-->>Recognizer: ✓
deactivate TxManager
Recognizer->>TxManager: CloseSegment(source segment)
activate TxManager
TxManager-->>Recognizer: ✓
deactivate TxManager
end
Recognizer-->>ChargeService: RecognizedAmount, LedgerGroupID
deactivate Recognizer
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsTimed out fetching pipeline failures after 30000ms 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. Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
openmeter/billing/charges/service/service.go (1)
87-99:⚠️ Potential issue | 🟠 MajorDon't let missing recognizer wiring degrade into a silent success.
Defaulting to
recognizer.NoopService{}here means a production wiring miss quietly disables revenue recognition and still returns nil everywhere. For accounting flows, that's a pretty dangerous failure mode because it looks identical to “nothing eligible to recognize”. I’d rather makeRecognizerServicerequired inConfig.Validate()and have tests/helpers passrecognizer.NoopService{}explicitly when they really want the stub.Suggested change
func (c Config) Validate() error { var errs []error @@ if c.MetaAdapter == nil { errs = append(errs, errors.New("meta adapter cannot be null")) } + + if c.RecognizerService == nil { + errs = append(errs, errors.New("recognizer service cannot be null")) + } return errors.Join(errs...) } @@ - if config.RecognizerService == nil { - config.RecognizerService = recognizer.NoopService{} - } - svc := &service{ @@ recognizerService: config.RecognizerService,🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/service/service.go` around lines 87 - 99, Currently the constructor silently replaces a missing config.RecognizerService with recognizer.NoopService{}, which can mask production wiring errors; instead make RecognizerService required by validating it in Config.Validate() (return an error if config.RecognizerService == nil), remove the fallback assignment of recognizer.NoopService{} in the service constructor, and ensure the service's recognizerService field is populated from config.RecognizerService; update tests/helpers to explicitly pass recognizer.NoopService{} where a stub is desired.
🧹 Nitpick comments (4)
openmeter/ledger/routingrules/routingrules.go (1)
44-45: Small perf win: avoid cloning entries twiceLine 44 and Line 45 each call
tx.Entries(). Since this returns a cloned slice, fetching once avoids an extra allocation/copy in validation.Suggested refactor
func (r RequireUniqueSubAccountsRule) Validate(tx TxView) error { - seen := make(map[string]struct{}, len(tx.Entries())) - for _, entry := range tx.Entries() { + entries := tx.Entries() + seen := make(map[string]struct{}, len(entries)) + for _, entry := range entries { subAccountID := entry.Entry().PostingAddress().SubAccountID() if _, ok := seen[subAccountID]; ok { return ledger.ErrRoutingRuleViolated.WithAttrs(models.Attributes{ "reason": "duplicate_sub_account_entry", "sub_account_id": subAccountID, }) }As per coding guidelines: “Performance should be a priority in critical code paths.”
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/ledger/routingrules/routingrules.go` around lines 44 - 45, The code calls tx.Entries() twice causing an extra clone; fetch the entries once into a local variable (e.g., entries := tx.Entries()) and use that variable in both the len() for the seen map allocation and in the for _, entry := range loop (referencing tx.Entries() and seen in routingrules.go) so you avoid the duplicate allocation/copy.openmeter/ledger/transactions/correction_leg.go (1)
33-105: Make leg allocation deterministic inside the allocator.Right now allocation depends on incoming
sourceEntriesorder. In this path, stable ordering helps reproducibility and reduces “same input, different posting split” surprises.♻️ Suggested change
import ( "cmp" "fmt" + "slices" "github.com/alpacahq/alpacadecimal" @@ func allocateCorrectionLegs( sourceEntries []ledger.Entry, counterpartEntries []ledger.Entry, @@ ) ([]correctionPosting, error) { + // Keep allocation deterministic regardless of caller-side ordering. + sourceEntries = append([]ledger.Entry(nil), sourceEntries...) + slices.SortFunc(sourceEntries, compareSubAccountID) + counterpartAddressesByKey := make(map[routePairingKey]ledger.PostingAddress, len(counterpartEntries))🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/ledger/transactions/correction_leg.go` around lines 33 - 105, Allocation varies with sourceEntries order; make it deterministic by sorting the constructed legs before the reverse allocation loop. In allocateCorrectionLegs, after building the legs slice (and before computing available/using it in the remaining loop) perform a stable sort (e.g., sort.SliceStable) on legs using the deterministic key produced by keyForAddress(leg.sourceAddress) and tie-breaker like leg.sourceAddress.String() or SubAccountID so identical inputs always produce the same posting splits; keep the reverse iteration (idx := len(legs)-1 ... ) logic unchanged.openmeter/ledger/recognizer/recognize.go (1)
220-226: Note:minDecimalis duplicated.This helper also exists in
openmeter/ledger/collector/correct.go(line 510-516) andopenmeter/billing/charges/lineage/service.go(exported aslineage.MinDecimal). Consider extracting to a shared utility to reduce duplication.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/ledger/recognizer/recognize.go` around lines 220 - 226, The minDecimal implementation is duplicated across recognizer (minDecimal), collector (minDecimal) and billing (lineage.MinDecimal); extract a single exported helper (e.g., MinDecimal) that accepts and returns alpacadecimal.Decimal into a small shared package (e.g., a new openmeter/decimal or openmeter/internal/decimalutil package), replace the local minDecimal implementations with calls to that shared MinDecimal, and update imports/usages in recognizer (replace minDecimal), collector (replace minDecimal), and lineage (use the new shared MinDecimal) so only one canonical implementation remains.openmeter/ledger/recognizer/service_test.go (1)
118-146: Unusedstatevariable can be removed.The
statecomputed at line 118 is never used - it's just blanked at line 145. The actual state is derived internally byCreateInitialLineagesvia the annotations. You can safely remove both lines.♻️ Suggested cleanup
func (e *recognizerTestEnv) createLineageForRealization(t *testing.T, chargeID, realizationID string, amount alpacadecimal.Decimal, originKind creditrealization.LineageOriginKind) { t.Helper() e.ensureCharge(t, chargeID) - state := creditrealization.InitialLineageSegmentState(originKind) - err := e.lineage.CreateInitialLineages(t.Context(), lineage.CreateInitialLineagesInput{ Namespace: e.Namespace, ChargeID: chargeID, CustomerID: e.CustomerID.ID, Currency: e.Currency, Realizations: creditrealization.Realizations{ { CreateInput: creditrealization.CreateInput{ ID: realizationID, Amount: amount, Type: creditrealization.TypeAllocation, ServicePeriod: timeutil.ClosedPeriod{ From: clock.Now().Add(-24 * time.Hour), To: clock.Now(), }, LedgerTransaction: ledgertransaction.GroupReference{ TransactionGroupID: "test-group-" + realizationID, }, Annotations: creditrealization.LineageAnnotations(originKind), }, }, }, }) require.NoError(t, err) - - _ = state }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/ledger/recognizer/service_test.go` around lines 118 - 146, The local variable "state" created by calling InitialLineageSegmentState(originKind) is unused and then explicitly blanked; remove the unused declaration and the subsequent "_ = state" line to clean up the test; specifically delete the call/assignment to state (InitialLineageSegmentState(originKind)) and the discard line so only the call to e.lineage.CreateInitialLineages(...) remains in the Test/recognizer/service_test.go test around where state is declared.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/billing/charges/lineage/lineage_test.go`:
- Around line 12-25: Add a table-driven test to exercise all new Validate()
failure branches: create cases for missing SourceState (nil), SourceState ==
LineageSegmentStateEarningsRecognized, SourceState ==
LineageSegmentStateAdvanceBackfilled with nil BackingTransactionGroupID, and the
symmetric missing BackingTransactionGroupID when State is earnings_recognized;
for each case construct a Segment (use the existing BackingTransactionGroupID
and sourceState symbols like LineageSegmentStateAdvanceBackfilled and
LineageSegmentStateEarningsRecognized) call Segment.Validate(), and assert
require.Error and require.ErrorContains with the specific expected message for
that branch (e.g., "source state is required", "source state must be
advance_backfilled", "source backing transaction group id is required when
source state is advance_backfilled", etc.).
In `@openmeter/billing/charges/lineage/lineage.go`:
- Around line 62-75: Ensure the code validates the SourceState enum value itself
before applying special-case logic: after checking s.SourceState is not nil,
call the enum's Validate() method (e.g., s.SourceState.Validate()) and append
any validation error to errs; only proceed to the specific checks that compare
*s.SourceState to creditrealization.LineageSegmentStateEarningsRecognized or
LineageSegmentStateAdvanceBackfilled if Validate() succeeds. Update the
switch/order in the earnings_recognized case in Validate() to perform the nil
check, then call Validate() on s.SourceState, and then run the existing
comparisons and source backing-id requirement checks.
In `@openmeter/billing/charges/lineage/service.go`:
- Around line 192-215: The validation currently allows invalid combos:
non-earnings_recognized segments may carry a SourceBackingTransactionGroupID and
earnings_recognized only checks the backing ID for one SourceState case. Update
the switch on i.State (creditrealization.LineageSegmentStateEarningsRecognized)
so that: 1) when i.State == LineageSegmentStateEarningsRecognized require
i.SourceState != nil, call i.SourceState.Validate(), reject if *i.SourceState ==
LineageSegmentStateEarningsRecognized, and if *i.SourceState ==
LineageSegmentStateAdvanceBackfilled require a non-empty
i.SourceBackingTransactionGroupID; also if SourceState is present but not
AdvanceBackfilled, ensure SourceBackingTransactionGroupID is nil (or treated as
invalid if provided); 2) in the default branch (non-earnings_recognized) reject
any provided i.SourceState and also reject any provided
i.SourceBackingTransactionGroupID (nil only allowed) by appending errors to
errs.
In `@openmeter/billing/charges/service/advance.go`:
- Around line 111-132: The current flow performs advancement inside
transaction.Run(...) (so advancedCharges are already persisted) and then calls
s.recognizerService.RecognizeEarnings inside s.billingService.WithLock which can
return an error after durable side effects; to fix, either move the
RecognizeEarnings calls into the same transaction/lock that creates the advances
(so do currency collection and call RecognizeEarnings before committing the
transaction.Run block), or convert recognition here into a best-effort follow-up
(do not return an error on failure—log the error and continue) so the API does
not report failure after commit; update the code paths around collectCurrencies,
transaction.Run(...), and s.billingService.WithLock/RecognizeEarnings
accordingly.
In `@openmeter/ledger/routingrules/routingrules_test.go`:
- Around line 104-123: The test
TestDefaultValidator_RejectsDuplicateSubAccountEntries currently uses
addressForRoute with ledger.AccountTypeCustomerFBO which also triggers
RequireFBOCostBasisTranslationRule, so fix it by creating entries that only
violate the duplicate-subaccount rule: change the address construction in
addressForRoute to use a non-FBO account type (e.g., ledger.AccountTypeCustomer)
or otherwise ensure the route passed to addressForRoute satisfies the FBO
cost-basis translation rule, then call DefaultValidator.ValidateEntries with two
ledger.EntryInput instances that share the same subaccount/address but are
otherwise valid; this isolates the duplicate-subaccount failure and ensures the
test fails only for that uniqueness rule.
---
Outside diff comments:
In `@openmeter/billing/charges/service/service.go`:
- Around line 87-99: Currently the constructor silently replaces a missing
config.RecognizerService with recognizer.NoopService{}, which can mask
production wiring errors; instead make RecognizerService required by validating
it in Config.Validate() (return an error if config.RecognizerService == nil),
remove the fallback assignment of recognizer.NoopService{} in the service
constructor, and ensure the service's recognizerService field is populated from
config.RecognizerService; update tests/helpers to explicitly pass
recognizer.NoopService{} where a stub is desired.
---
Nitpick comments:
In `@openmeter/ledger/recognizer/recognize.go`:
- Around line 220-226: The minDecimal implementation is duplicated across
recognizer (minDecimal), collector (minDecimal) and billing
(lineage.MinDecimal); extract a single exported helper (e.g., MinDecimal) that
accepts and returns alpacadecimal.Decimal into a small shared package (e.g., a
new openmeter/decimal or openmeter/internal/decimalutil package), replace the
local minDecimal implementations with calls to that shared MinDecimal, and
update imports/usages in recognizer (replace minDecimal), collector (replace
minDecimal), and lineage (use the new shared MinDecimal) so only one canonical
implementation remains.
In `@openmeter/ledger/recognizer/service_test.go`:
- Around line 118-146: The local variable "state" created by calling
InitialLineageSegmentState(originKind) is unused and then explicitly blanked;
remove the unused declaration and the subsequent "_ = state" line to clean up
the test; specifically delete the call/assignment to state
(InitialLineageSegmentState(originKind)) and the discard line so only the call
to e.lineage.CreateInitialLineages(...) remains in the
Test/recognizer/service_test.go test around where state is declared.
In `@openmeter/ledger/routingrules/routingrules.go`:
- Around line 44-45: The code calls tx.Entries() twice causing an extra clone;
fetch the entries once into a local variable (e.g., entries := tx.Entries()) and
use that variable in both the len() for the seen map allocation and in the for
_, entry := range loop (referencing tx.Entries() and seen in routingrules.go) so
you avoid the duplicate allocation/copy.
In `@openmeter/ledger/transactions/correction_leg.go`:
- Around line 33-105: Allocation varies with sourceEntries order; make it
deterministic by sorting the constructed legs before the reverse allocation
loop. In allocateCorrectionLegs, after building the legs slice (and before
computing available/using it in the remaining loop) perform a stable sort (e.g.,
sort.SliceStable) on legs using the deterministic key produced by
keyForAddress(leg.sourceAddress) and tie-breaker like leg.sourceAddress.String()
or SubAccountID so identical inputs always produce the same posting splits; keep
the reverse iteration (idx := len(legs)-1 ... ) logic unchanged.
🪄 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: 3e1d2fa7-4f65-4056-b674-71ca3ecb8b18
⛔ Files ignored due to path filters (10)
openmeter/ent/db/creditrealizationlineagesegment.gois excluded by!**/ent/db/**openmeter/ent/db/creditrealizationlineagesegment/creditrealizationlineagesegment.gois excluded by!**/ent/db/**openmeter/ent/db/creditrealizationlineagesegment/where.gois excluded by!**/ent/db/**openmeter/ent/db/creditrealizationlineagesegment_create.gois excluded by!**/ent/db/**openmeter/ent/db/creditrealizationlineagesegment_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/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (31)
AGENTS.mdapp/common/billing.goapp/common/charges.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.goopenmeter/billing/charges/service/advance.goopenmeter/billing/charges/service/invoice.goopenmeter/billing/charges/service/service.goopenmeter/ent/schema/creditrealizationlineage.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/collector/correct.goopenmeter/ledger/recognizer/noop.goopenmeter/ledger/recognizer/recognize.goopenmeter/ledger/recognizer/service.goopenmeter/ledger/recognizer/service_test.goopenmeter/ledger/routingrules/defaults.goopenmeter/ledger/routingrules/routingrules.goopenmeter/ledger/routingrules/routingrules_test.goopenmeter/ledger/transactions/accrual.goopenmeter/ledger/transactions/accrual_test.goopenmeter/ledger/transactions/correction_leg.goopenmeter/ledger/transactions/earnings.goopenmeter/ledger/transactions/earnings_test.gotest/credits/sanity_test.gotools/migrate/migrations/20260426112051_add_credit_realization_lineage_segment_source.down.sqltools/migrate/migrations/20260426112051_add_credit_realization_lineage_segment_source.up.sql
| func TestSegmentValidateRequiresSourceBackingTransactionGroupForAdvanceBackfilledSource(t *testing.T) { | ||
| sourceState := creditrealization.LineageSegmentStateAdvanceBackfilled | ||
| backingTransactionGroupID := "recognition-txg" | ||
|
|
||
| err := Segment{ | ||
| Amount: alpacadecimal.NewFromInt(10), | ||
| State: creditrealization.LineageSegmentStateEarningsRecognized, | ||
| BackingTransactionGroupID: &backingTransactionGroupID, | ||
| SourceState: &sourceState, | ||
| }.Validate() | ||
|
|
||
| require.Error(t, err) | ||
| require.ErrorContains(t, err, "source backing transaction group id is required when source state is advance_backfilled") | ||
| } |
There was a problem hiding this comment.
Add coverage for the other new validation branches.
Nice start, but this only exercises the advance_backfilled source case. The new Validate() logic also added distinct failure paths for missing SourceState, SourceState == earnings_recognized, and missing BackingTransactionGroupID on both state variants, so those can still regress unnoticed. A small table-driven test here would make this much safer.
As per coding guidelines, "**/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@openmeter/billing/charges/lineage/lineage_test.go` around lines 12 - 25, Add
a table-driven test to exercise all new Validate() failure branches: create
cases for missing SourceState (nil), SourceState ==
LineageSegmentStateEarningsRecognized, SourceState ==
LineageSegmentStateAdvanceBackfilled with nil BackingTransactionGroupID, and the
symmetric missing BackingTransactionGroupID when State is earnings_recognized;
for each case construct a Segment (use the existing BackingTransactionGroupID
and sourceState symbols like LineageSegmentStateAdvanceBackfilled and
LineageSegmentStateEarningsRecognized) call Segment.Validate(), and assert
require.Error and require.ErrorContains with the specific expected message for
that branch (e.g., "source state is required", "source state must be
advance_backfilled", "source backing transaction group id is required when
source state is advance_backfilled", etc.).
| case creditrealization.LineageSegmentStateEarningsRecognized: | ||
| if s.BackingTransactionGroupID == nil || *s.BackingTransactionGroupID == "" { | ||
| errs = append(errs, errors.New("backing transaction group id is required for earnings_recognized")) | ||
| } | ||
| switch { | ||
| case s.SourceState == nil: | ||
| errs = append(errs, errors.New("source state is required for earnings_recognized")) | ||
| case *s.SourceState == creditrealization.LineageSegmentStateEarningsRecognized: | ||
| errs = append(errs, errors.New("source state cannot be earnings_recognized")) | ||
| case *s.SourceState == creditrealization.LineageSegmentStateAdvanceBackfilled: | ||
| if s.SourceBackingTransactionGroupID == nil || *s.SourceBackingTransactionGroupID == "" { | ||
| errs = append(errs, errors.New("source backing transaction group id is required when source state is advance_backfilled")) | ||
| } | ||
| } |
There was a problem hiding this comment.
Validate SourceState itself before checking the special cases.
Right now any non-nil, non-earnings_recognized junk value gets through here because we never call Validate() on SourceState. That means an invalid persisted source state can make it into lineage and only blow up later in correction/planning code.
Suggested change
case creditrealization.LineageSegmentStateEarningsRecognized:
if s.BackingTransactionGroupID == nil || *s.BackingTransactionGroupID == "" {
errs = append(errs, errors.New("backing transaction group id is required for earnings_recognized"))
}
switch {
case s.SourceState == nil:
errs = append(errs, errors.New("source state is required for earnings_recognized"))
+ case (*s.SourceState).Validate() != nil:
+ errs = append(errs, fmt.Errorf("source state: %w", (*s.SourceState).Validate()))
case *s.SourceState == creditrealization.LineageSegmentStateEarningsRecognized:
errs = append(errs, errors.New("source state cannot be earnings_recognized"))
case *s.SourceState == creditrealization.LineageSegmentStateAdvanceBackfilled:
if s.SourceBackingTransactionGroupID == nil || *s.SourceBackingTransactionGroupID == "" {
errs = append(errs, errors.New("source backing transaction group id is required when source state is advance_backfilled"))
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@openmeter/billing/charges/lineage/lineage.go` around lines 62 - 75, Ensure
the code validates the SourceState enum value itself before applying
special-case logic: after checking s.SourceState is not nil, call the enum's
Validate() method (e.g., s.SourceState.Validate()) and append any validation
error to errs; only proceed to the specific checks that compare *s.SourceState
to creditrealization.LineageSegmentStateEarningsRecognized or
LineageSegmentStateAdvanceBackfilled if Validate() succeeds. Update the
switch/order in the earnings_recognized case in Validate() to perform the nil
check, then call Validate() on s.SourceState, and then run the existing
comparisons and source backing-id requirement checks.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/billing/charges/service/advance.go`:
- Around line 103-105: collectCurrencies currently swallows errors from
As*Charge() and skips malformed charge wrappers, so AdvanceCharges may commit
while earnings recognition misses charges; update the flow to fail closed by
making collectCurrencies return an error (or provide a companion function that
returns (currencies, error)) and propagate that error from AdvanceCharges before
calling s.recognizeCustomerEarnings; specifically, change the call site around
s.recognizeCustomerEarnings(ctx, input.Customer,
collectCurrencies(advancedCharges)...) to handle and return any error from
collectCurrencies, and update collectCurrencies (and any loop using As*Charge())
to surface the As*Charge() failures instead of skipping them, applying the same
fix to the similar code paths referenced in the 116-152 region.
🪄 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: 6f5671a8-db05-4256-901c-26e520931cdc
📒 Files selected for processing (5)
openmeter/billing/charges/service/advance.goopenmeter/billing/charges/service/create.goopenmeter/billing/charges/service/creditpurchase.goopenmeter/billing/charges/service/invoice.goopenmeter/billing/charges/service/recognition.go
🚧 Files skipped from review as they are similar to previous changes (1)
- openmeter/billing/charges/service/invoice.go
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
openmeter/billing/charges/lineage/adapter/lineage.go (1)
96-109: ⚡ Quick winFilter out fully closed lineages here too.
WithSegments(...ClosedAtIsNil())only trims the preloaded edge; the root query still returns every lineage for that customer/currency, including ones with zero active segments. On the recognition path that will grow with history and add avoidable DB/app work.Suggested tweak
lineages, err := tx.db.CreditRealizationLineage.Query(). Where( creditrealizationlineage.Namespace(input.Namespace), creditrealizationlineage.CustomerIDEQ(input.CustomerID), creditrealizationlineage.CurrencyEQ(input.Currency), + creditrealizationlineage.HasSegmentsWith( + creditrealizationlineagesegment.ClosedAtIsNil(), + ), ).As per coding guidelines, performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations should be vetted for potential performance bottlenecks.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/lineage/adapter/lineage.go` around lines 96 - 109, The LoadLineagesByCustomer root query currently preloads only open segments via WithSegments(...ClosedAtIsNil()) but still returns lineages that have no active segments; update the root creditrealizationlineage query in adapter.LoadLineagesByCustomer to only select lineages that have at least one open segment by adding a predicate such as HasSegmentsWith(creditrealizationlineagesegment.ClosedAtIsNil()) (or the equivalent ent predicate) alongside the existing Namespace/CustomerIDEQ/CurrencyEQ filters so the DB returns only lineages with active segments and avoids loading stale/empty lineages.openmeter/ledger/recognizer/service_test.go (1)
186-225: ⚡ Quick winPlease add one
advance_backfilledrecognition case here.These tests cover
real_credit, but the new correction path also relies onSourceBackingTransactionGroupIDbeing preserved when the recognized segment came fromadvance_backfilled. A small case that seeds a backfilled segment and asserts that metadata survives onto theearnings_recognizedsegment would close the main gap in this file.As per coding guidelines,
**/*_test.go: Make sure the tests are comprehensive and cover the changes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/ledger/recognizer/service_test.go` around lines 186 - 225, Add a parallel sub-case in TestRecognizeEarnings_DeterministicAllocationAndSegmentTransition that seeds a lineage segment originating from advance_backfilled (use env.createLineageForRealization or the equivalent helper but pass creditrealization.LineageOriginKindAdvanceBackfilled), ensure the seeded segment has a non-nil SourceBackingTransactionGroupID, run recognizer.RecognizeEarnings as in the test, and assert the transitioned segment still has the same SourceBackingTransactionGroupID and SourceState preserved (compare seg.SourceBackingTransactionGroupID and seg.SourceState on the earnings_recognized segment to the original values) so the advance_backfilled metadata survives the transition.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/ledger/recognizer/recognize.go`:
- Around line 101-102: The segment close timestamp currently uses clock.Now()
causing ledger vs lineage timeline drift for backfilled/replayed recognitions;
change allocateRecognition(ctx, eligible, actualAmount, groupID) to accept the
recognition timestamp (in.At) and thread that timestamp through to wherever the
segment transition/close is set so the transition uses the passed-in time
instead of calling clock.Now(); update both call sites (the one at the shown
allocateRecognition invocation and the other occurrence around lines 146-149)
and the allocateRecognition signature/implementation (and any helper that sets
the segment close time) to use the provided timestamp for the lineage
transition.
---
Nitpick comments:
In `@openmeter/billing/charges/lineage/adapter/lineage.go`:
- Around line 96-109: The LoadLineagesByCustomer root query currently preloads
only open segments via WithSegments(...ClosedAtIsNil()) but still returns
lineages that have no active segments; update the root creditrealizationlineage
query in adapter.LoadLineagesByCustomer to only select lineages that have at
least one open segment by adding a predicate such as
HasSegmentsWith(creditrealizationlineagesegment.ClosedAtIsNil()) (or the
equivalent ent predicate) alongside the existing
Namespace/CustomerIDEQ/CurrencyEQ filters so the DB returns only lineages with
active segments and avoids loading stale/empty lineages.
In `@openmeter/ledger/recognizer/service_test.go`:
- Around line 186-225: Add a parallel sub-case in
TestRecognizeEarnings_DeterministicAllocationAndSegmentTransition that seeds a
lineage segment originating from advance_backfilled (use
env.createLineageForRealization or the equivalent helper but pass
creditrealization.LineageOriginKindAdvanceBackfilled), ensure the seeded segment
has a non-nil SourceBackingTransactionGroupID, run recognizer.RecognizeEarnings
as in the test, and assert the transitioned segment still has the same
SourceBackingTransactionGroupID and SourceState preserved (compare
seg.SourceBackingTransactionGroupID and seg.SourceState on the
earnings_recognized segment to the original values) so the advance_backfilled
metadata survives the transition.
🪄 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: 230f0578-87ad-4c4b-b4b2-6599e59c3d29
⛔ Files ignored due to path filters (10)
openmeter/ent/db/creditrealizationlineagesegment.gois excluded by!**/ent/db/**openmeter/ent/db/creditrealizationlineagesegment/creditrealizationlineagesegment.gois excluded by!**/ent/db/**openmeter/ent/db/creditrealizationlineagesegment/where.gois excluded by!**/ent/db/**openmeter/ent/db/creditrealizationlineagesegment_create.gois excluded by!**/ent/db/**openmeter/ent/db/creditrealizationlineagesegment_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/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (34)
AGENTS.mdapp/common/billing.goapp/common/charges.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.goopenmeter/billing/charges/service/advance.goopenmeter/billing/charges/service/create.goopenmeter/billing/charges/service/creditpurchase.goopenmeter/billing/charges/service/invoice.goopenmeter/billing/charges/service/recognition.goopenmeter/billing/charges/service/service.goopenmeter/ent/schema/creditrealizationlineage.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/collector/correct.goopenmeter/ledger/recognizer/noop.goopenmeter/ledger/recognizer/recognize.goopenmeter/ledger/recognizer/service.goopenmeter/ledger/recognizer/service_test.goopenmeter/ledger/routingrules/defaults.goopenmeter/ledger/routingrules/routingrules.goopenmeter/ledger/routingrules/routingrules_test.goopenmeter/ledger/transactions/accrual.goopenmeter/ledger/transactions/accrual_test.goopenmeter/ledger/transactions/correction_leg.goopenmeter/ledger/transactions/earnings.goopenmeter/ledger/transactions/earnings_test.gotest/credits/sanity_test.gotools/migrate/migrations/20260430095237_add_credit_realization_lineage_segment_source.down.sqltools/migrate/migrations/20260430095237_add_credit_realization_lineage_segment_source.up.sql
✅ Files skipped from review due to trivial changes (5)
- tools/migrate/migrations/20260430095237_add_credit_realization_lineage_segment_source.up.sql
- tools/migrate/migrations/20260430095237_add_credit_realization_lineage_segment_source.down.sql
- AGENTS.md
- openmeter/ledger/recognizer/noop.go
- openmeter/billing/charges/service/advance.go
🚧 Files skipped from review as they are similar to previous changes (13)
- openmeter/billing/charges/lineage/lineage_test.go
- openmeter/billing/charges/service/invoice.go
- openmeter/ledger/routingrules/routingrules_test.go
- openmeter/ent/schema/creditrealizationlineage.go
- openmeter/ledger/transactions/accrual_test.go
- openmeter/billing/charges/service/service.go
- openmeter/billing/charges/service/recognition.go
- openmeter/billing/charges/service/creditpurchase.go
- openmeter/billing/charges/lineage/lineage.go
- openmeter/ledger/recognizer/service.go
- openmeter/ledger/chargeadapter/usagebased_test.go
- openmeter/ledger/transactions/earnings_test.go
- openmeter/ledger/transactions/accrual.go
| return err | ||
| } | ||
|
|
||
| return s.recognizeEarningsForInvoice(ctx, invoice) |
There was a problem hiding this comment.
just FYI: This will be deprecated in favor of InvoiceLineEngines. Once I am cleaning this up I can always move the invoication.
| func (s *service) recognizeEarningsForInvoice(ctx context.Context, invoice billing.StandardInvoice) error { | ||
| return s.recognizeCustomerEarnings(ctx, invoice.CustomerID(), invoice.Currency) | ||
| } | ||
|
|
There was a problem hiding this comment.
nit: let's just inline it, one less redirection and improves code readability (esp. that it's not used by anything else).
| seen := make(map[currencyx.Code]bool) | ||
| out := make([]currencyx.Code, 0) | ||
|
|
||
| for _, c := range chargeList { |
There was a problem hiding this comment.
What about just adding a GetCurrency to the ChargeAccessor interface?
Then you can use lo.Uniq(lo.Map())
| Namespace: cp.Namespace, | ||
| ID: cp.Intent.CustomerID, | ||
| }, | ||
| }] = struct{}{} |
There was a problem hiding this comment.
maybe we can add GetCustomerID() to the common accessor interface.
Then this can become a lo.Uniq(lo.MapFilter
| return nil | ||
| } | ||
|
|
||
| func uniqueCurrencies(currencies []currencyx.Code) []currencyx.Code { |
| if config.RecognizerService == nil { | ||
| config.RecognizerService = recognizer.NoopService{} | ||
| } |
There was a problem hiding this comment.
please mandate it in Validate an default in the tests.
| creditedKeys := make(map[routePairingKey]struct{}, len(earningsSubAccByKey)) | ||
| for _, collection := range collections { | ||
| key := t.routePairingKey(collection.subAccount.Address()) | ||
| if _, ok := creditedKeys[key]; ok { |
There was a problem hiding this comment.
In general more comments for the tricky parts would be super awsome (e.g. why we are booking all collections and given earnings are preallocated we only need to book those once).
Even then it might be easier to iterate over earningsSubAccByKey. If not then it would be great if at least it's documented that we use this approach so that the entries order is governed by the collected entries.
| CustomerID customer.CustomerID | ||
| At time.Time | ||
| Currency currencyx.Code | ||
| Reason string |
|
|
||
| Keep domain test helpers under `openmeter/.../testutils` independent from `app/common`. Build test dependencies from the underlying package constructors (repos, adapters, services, `lockr`) instead of importing the application wiring layer, or unrelated wiring additions can create test-only import cycles. | ||
|
|
||
| When extending `openmeter/billing/charges/service.Config` with a new collaborator, keep test setup compatibility in mind: either provide a safe default in `service.New(...)` (for optional/runtime-pluggable dependencies) or update `openmeter/billing/charges/service/base_test.go` at the same time. Most charge service suites construct the service directly through that base setup. |
There was a problem hiding this comment.
This belongs to the charges skill, so please remove it from here, but please don't add optional collaborators there.
| if input.BackingTransactionGroupID != nil { | ||
| create = create.SetBackingTransactionGroupID(*input.BackingTransactionGroupID) | ||
| } | ||
| if input.SourceState != nil { | ||
| create = create.SetSourceState(*input.SourceState) | ||
| } | ||
| if input.SourceBackingTransactionGroupID != nil { | ||
| create = create.SetSourceBackingTransactionGroupID(*input.SourceBackingTransactionGroupID) | ||
| } |
There was a problem hiding this comment.
nit: here you could use SetNillable* helps with readability.
Summary
Adds ledger-backed revenue recognition for customer credit earnings, including lineage tracking and correction support.
What changed
ledger/recognizerservice for recognizing eligible accrued credit revenue into earnings.Notes
Summary by CodeRabbit
Release Notes
New Features
Improvements