Skip to content

feat(ledger): revenue recognition - #4230

Merged
GAlexIHU merged 6 commits into
mainfrom
feat/revrecog
Apr 30, 2026
Merged

GAlexIHU merged 6 commits into
mainfrom
feat/revrecog

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds ledger-backed revenue recognition for customer credit earnings, including lineage tracking and correction support.

What changed

  • Added ledger/recognizer service for recognizing eligible accrued credit revenue into earnings.
  • Wired revenue recognition into charge advancement and invoice lifecycle paths.
  • Extended credit realization lineage segments with source state/backing transaction group metadata so recognized segments can preserve provenance for later correction.
  • Added earnings correction support in the existing collector correction flow.
  • Refactored correction leg planning to avoid cost-basis-only collisions and coalesce postings by subaccount.
  • Added a routing rule preventing duplicate subaccount entries within a single ledger transaction.
  • Added migration/codegen for new lineage segment fields.
  • Added/expanded coverage across:
    • recognizer service
    • earnings/accrual correction templates
    • charge adapter correction tests
    • credit sanity tests
    • lineage validation
    • routing rules

Notes

  • Recognition runs transactionally with ledger + lineage updates committed together.
  • Correction remains charge-scoped through the existing correction flow.
  • revrecog highlights that current lineage representation is not the right data structure. it works for current purposes, but if we keep building on top of it that might warrant a rewrite to a proper graph

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced automatic earnings recognition for credit purchases, triggered when charges are created or invoices are finalized.
    • Enhanced credit lineage tracking with source attribution to support earnings reversal on charge corrections.
    • Added earnings tracking and allocation across multiple cost bases.
  • Improvements

    • Strengthened routing validation to prevent duplicate sub-account entries.

@coderabbitai

coderabbitai Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This PR introduces earnings recognition for credit purchases, wiring a new recognizer.Service throughout the billing system to track and reconcile recognized revenue against lineage segments. Recognition is triggered after advance charges, invoice processing, and credit purchase events, with correction logic to reverse recognized earnings when transactions are amended.

Changes

Cohort / File(s) Summary
Recognizer Service Foundation
openmeter/ledger/recognizer/service.go, openmeter/ledger/recognizer/recognize.go, openmeter/ledger/recognizer/noop.go, openmeter/ledger/recognizer/service_test.go
New recognizer.Service interface and implementation to load eligible lineages, filter recognizable segments, resolve earnings transactions, and allocate recognition across segments with tracking of source state/backing transaction metadata.
Lineage Schema & Domain Extensions
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/lineage/adapter/lineage.go, openmeter/ent/schema/creditrealizationlineage.go
Add earnings_recognized segment state, source state/backing transaction tracking, validation rules for earnings segments, and adapter methods to load/persist lineages with source metadata.
Charges Service Wiring
app/common/billing.go, app/common/charges.go, openmeter/billing/charges/service/service.go, openmeter/billing/charges/testutils/service.go, openmeter/billing/charges/service/base_test.go
Wire RecognizerService dependency into charges service config and registry, with test utilities defaulting to no-op implementation.
Recognition Trigger Handlers
openmeter/billing/charges/service/advance.go, openmeter/billing/charges/service/invoice.go, openmeter/billing/charges/service/creditpurchase.go, openmeter/billing/charges/service/create.go, openmeter/billing/charges/service/recognition.go
Invoke earnings recognition after advances, invoices, and credit purchases by calling recognizeCustomerEarnings with deduplicated customer/currency scopes.
Charge Type Accessors
openmeter/billing/charges/charge.go, openmeter/billing/charges/flatfee/charge.go, openmeter/billing/charges/creditpurchase/charge.go, openmeter/billing/charges/usagebased/charge.go, openmeter/billing/charges/meta/charge.go
Add GetCustomerID() and GetCurrency() methods across charge types to extract customer and currency for earnings recognition.
Ledger Transaction Templates & Rules
openmeter/ledger/transactions/accrual.go, openmeter/ledger/transactions/accrual_test.go, openmeter/ledger/transactions/earnings.go, openmeter/ledger/transactions/earnings_test.go, openmeter/ledger/transactions/correction_leg.go, openmeter/ledger/routingrules/routingrules.go, openmeter/ledger/routingrules/routingrules_test.go, openmeter/ledger/routingrules/defaults.go, openmeter/ledger/collector/correct.go
Implement earnings recognition and correction transaction templates with route-pairing logic, new RequireUniqueSubAccountsRule, segment correction reversal, and updated sorting precedence for EarningsRecognized state.
Database Migrations
tools/migrate/migrations/20260430095237_add_credit_realization_lineage_segment_source.up.sql, tools/migrate/migrations/20260430095237_add_credit_realization_lineage_segment_source.down.sql
Add source_state and source_backing_transaction_group_id nullable columns to credit_realization_lineage_segments table.
Integration Tests
openmeter/ledger/chargeadapter/flatfee_test.go, openmeter/ledger/chargeadapter/usagebased_test.go, test/credits/sanity_test.go
Extend test environments with lineage/recognizer services, validate correction behavior after earnings recognition, and assert segment state transitions and ledger balance reversals.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

release-note/feature, area/billing

Suggested reviewers

  • tothandras
  • turip
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.87% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(ledger): revenue recognition' accurately captures the primary change—implementing revenue recognition in the ledger system. It's concise, specific, and directly reflects the main objective of this substantial PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/revrecog

Warning

Review ran into problems

🔥 Problems

Timed 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.

❤️ Share
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.

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

@GAlexIHU GAlexIHU added the release-note/ignore Ignore this change when generating release notes label Apr 29, 2026
@GAlexIHU
GAlexIHU marked this pull request as ready for review April 29, 2026 14:21
@GAlexIHU
GAlexIHU requested a review from a team as a code owner April 29, 2026 14:21

@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: 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 | 🟠 Major

Don'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 make RecognizerService required in Config.Validate() and have tests/helpers pass recognizer.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 twice

Line 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 sourceEntries order. 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: minDecimal is duplicated.

This helper also exists in openmeter/ledger/collector/correct.go (line 510-516) and openmeter/billing/charges/lineage/service.go (exported as lineage.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: Unused state variable can be removed.

The state computed at line 118 is never used - it's just blanked at line 145. The actual state is derived internally by CreateInitialLineages via 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

📥 Commits

Reviewing files that changed from the base of the PR and between f6bdaa2 and 48ebfbe.

⛔ Files ignored due to path filters (10)
  • openmeter/ent/db/creditrealizationlineagesegment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/creditrealizationlineagesegment/creditrealizationlineagesegment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/creditrealizationlineagesegment/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/creditrealizationlineagesegment_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/creditrealizationlineagesegment_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/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (31)
  • AGENTS.md
  • app/common/billing.go
  • app/common/charges.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.go
  • openmeter/billing/charges/service/advance.go
  • openmeter/billing/charges/service/invoice.go
  • openmeter/billing/charges/service/service.go
  • openmeter/ent/schema/creditrealizationlineage.go
  • openmeter/ledger/chargeadapter/flatfee_test.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
  • openmeter/ledger/collector/correct.go
  • openmeter/ledger/recognizer/noop.go
  • openmeter/ledger/recognizer/recognize.go
  • openmeter/ledger/recognizer/service.go
  • openmeter/ledger/recognizer/service_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/accrual_test.go
  • openmeter/ledger/transactions/correction_leg.go
  • openmeter/ledger/transactions/earnings.go
  • openmeter/ledger/transactions/earnings_test.go
  • test/credits/sanity_test.go
  • tools/migrate/migrations/20260426112051_add_credit_realization_lineage_segment_source.down.sql
  • tools/migrate/migrations/20260426112051_add_credit_realization_lineage_segment_source.up.sql

Comment on lines +12 to +25
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")
}

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

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.).

Comment on lines +62 to +75
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"))
}
}

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 | 🟠 Major

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.

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 48ebfbe and 81c2f72.

📒 Files selected for processing (5)
  • openmeter/billing/charges/service/advance.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/creditpurchase.go
  • openmeter/billing/charges/service/invoice.go
  • openmeter/billing/charges/service/recognition.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/billing/charges/service/invoice.go

@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: 1

🧹 Nitpick comments (2)
openmeter/billing/charges/lineage/adapter/lineage.go (1)

96-109: ⚡ Quick win

Filter 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 win

Please add one advance_backfilled recognition case here.

These tests cover real_credit, but the new correction path also relies on SourceBackingTransactionGroupID being preserved when the recognized segment came from advance_backfilled. A small case that seeds a backfilled segment and asserts that metadata survives onto the earnings_recognized segment 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

📥 Commits

Reviewing files that changed from the base of the PR and between 81c2f72 and 75b0dbb.

⛔ Files ignored due to path filters (10)
  • openmeter/ent/db/creditrealizationlineagesegment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/creditrealizationlineagesegment/creditrealizationlineagesegment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/creditrealizationlineagesegment/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/creditrealizationlineagesegment_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/creditrealizationlineagesegment_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/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (34)
  • AGENTS.md
  • app/common/billing.go
  • app/common/charges.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.go
  • openmeter/billing/charges/service/advance.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/creditpurchase.go
  • openmeter/billing/charges/service/invoice.go
  • openmeter/billing/charges/service/recognition.go
  • openmeter/billing/charges/service/service.go
  • openmeter/ent/schema/creditrealizationlineage.go
  • openmeter/ledger/chargeadapter/flatfee_test.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
  • openmeter/ledger/collector/correct.go
  • openmeter/ledger/recognizer/noop.go
  • openmeter/ledger/recognizer/recognize.go
  • openmeter/ledger/recognizer/service.go
  • openmeter/ledger/recognizer/service_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/accrual_test.go
  • openmeter/ledger/transactions/correction_leg.go
  • openmeter/ledger/transactions/earnings.go
  • openmeter/ledger/transactions/earnings_test.go
  • test/credits/sanity_test.go
  • tools/migrate/migrations/20260430095237_add_credit_realization_lineage_segment_source.down.sql
  • tools/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)

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.

just FYI: This will be deprecated in favor of InvoiceLineEngines. Once I am cleaning this up I can always move the invoication.

Comment on lines +230 to +233
func (s *service) recognizeEarningsForInvoice(ctx context.Context, invoice billing.StandardInvoice) error {
return s.recognizeCustomerEarnings(ctx, invoice.CustomerID(), invoice.Currency)
}

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.

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 {

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.

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{}{}

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.

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 {

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.

lo.Uniq

SKILL issues :D

Comment on lines +87 to +89
if config.RecognizerService == nil {
config.RecognizerService = recognizer.NoopService{}
}

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.

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 {

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.

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.

Comment thread openmeter/ledger/recognizer/service.go Outdated
CustomerID customer.CustomerID
At time.Time
Currency currencyx.Code
Reason string

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.

Unused.

Comment thread AGENTS.md Outdated

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.

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.

This belongs to the charges skill, so please remove it from here, but please don't add optional collaborators there.

Comment on lines +228 to +236
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)
}

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.

nit: here you could use SetNillable* helps with readability.

@GAlexIHU
GAlexIHU merged commit d3a52b3 into main Apr 30, 2026
26 of 27 checks passed
@GAlexIHU
GAlexIHU deleted the feat/revrecog branch April 30, 2026 13:36

This branch was previously deployed

1 inactive deployment
dev — 45a92583 Deployed Apr 30, 2026 by GAlexIHU via Migration Checks #13967
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