Repository navigation
feat!: breakage - #4371
feat!: breakage#4371GAlexIHU wants to merge 13 commits into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughImplements expiring-credit breakage (plan/release/reopen), adds as-of balance/transaction filtering and BalanceQuery plumbing, entry identity/annotations and DB/migration changes, threads breakage through collectors/handlers/ledger, and adds templates, adapters, wiring, tests, and docs. ChangesExpiring Credits & Breakage
Ledger identity, templates, and annotations
Collector, corrector, and transactional plumbing
Balance, loaders, and customer-facing presentation
Tests & Docs
✨ Finishing Touches🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
Actionable comments posted: 11
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
openmeter/ledger/customerbalance/transactions.go (1)
137-145:⚠️ Potential issue | 🟠 Major | ⚡ Quick winApply the same
AsOfcutoff when computing running balances.Transactions are loaded with
AsOf, but the follow-up balance query at Line 172 currently defaults to “now”. For historical queries this can return incorrect per-itemBalance.Before/Aftervalues.Suggested patch
- loaderInput := creditTransactionLoaderInput{ + asOf := creditTransactionsAsOf(input.AsOf) + loaderInput := creditTransactionLoaderInput{ Limit: input.Limit, After: input.After, Before: input.Before, CustomerID: input.CustomerID, AccountID: accountID, Currency: input.Currency, - AsOf: creditTransactionsAsOf(input.AsOf), + AsOf: asOf, } @@ runningBalance, err := s.GetBalance(ctx, input.CustomerID, items[0].Currency, ledger.BalanceQuery{ After: lo.ToPtr(creditTransactionCursor(items[0])), + AsOf: lo.ToPtr(asOf), })Also applies to: 172-174
🤖 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/customerbalance/transactions.go` around lines 137 - 145, The running-balance computation is using the current time while transactions were loaded with a cutoff via creditTransactionsAsOf(input.AsOf), causing incorrect per-item Balance.Before/After for historical queries; update the running-balance query call to accept and use the same cutoff by passing creditTransactionsAsOf(input.AsOf) (or the AsOf value stored on loaderInput) into the balance calculation routine so the balance query uses the identical AsOf cutoff as creditTransactionLoaderInput and produces correct Balance.Before/After values.openmeter/ledger/historical/adapter/ledger.go (1)
476-534:⚠️ Potential issue | 🟠 Major | ⚡ Quick winScope the credit-movement subquery by namespace.
Right now the
HAVING SUM(amount)selector scans and groupscustomer_fboentries across every tenant, then the outer query filters back down toinput.Namespace. On a busy ledger table, this turns a single-customer list call into a cross-namespace aggregation.💡 Suggested fix
-func ledgerTransactionCreditMovementPredicate( - accountIDs []string, - currency *currencyx.Code, - movement ledger.ListTransactionsCreditMovement, -) (predicate.LedgerTransaction, error) { +func ledgerTransactionCreditMovementPredicate( + namespace string, + accountIDs []string, + currency *currencyx.Code, + movement ledger.ListTransactionsCreditMovement, +) (predicate.LedgerTransaction, error) { var having *sql.Predicate switch movement { case ledger.ListTransactionsCreditMovementPositive: having = scopedEntryAmountSumPredicate(">") @@ return func(s *sql.Selector) { s.Where(sql.In( s.C(ledgertransactiondb.FieldID), - scopedFBOMovementTransactionSelector(accountIDs, currency, having), + scopedFBOMovementTransactionSelector(namespace, accountIDs, currency, having), )) }, nil } func scopedFBOMovementTransactionSelector( + namespace string, accountIDs []string, currency *currencyx.Code, having *sql.Predicate, ) *sql.Selector { @@ selector := sql.Select(entries.C(ledgerentrydb.FieldTransactionID)). From(entries). + Where(sql.EQ(entries.C(ledgerentrydb.FieldNamespace), namespace)). Join(subAccounts). On(entries.C(ledgerentrydb.FieldSubAccountID), subAccounts.C(ledgersubaccountdb.FieldID)).As per coding guidelines, performance should be a priority in critical code paths, especially database operations.
🤖 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.go` around lines 476 - 534, The HAVING SUM(amount) subquery in scopedFBOMovementTransactionSelector is currently unscoped by namespace causing cross-tenant aggregation; modify the predicate chain to restrict the selector by namespace before GroupBy. Add a namespace parameter (e.g. namespace string) to scopedFBOMovementTransactionSelector and propagate it from ledgerTransactionCreditMovementPredicate, then apply a Where filter on the appropriate table column (e.g. entries.C(ledgerentrydb.FieldNamespace) or accounts.C(ledgeraccountdb.FieldNamespace) depending on your schema) so the JOIN/WHERE that narrows to customer_fbo and accountIDs runs inside the grouped subquery rather than only in the outer query. Ensure the new namespace argument is used wherever scopedFBOMovementTransactionSelector is called so the subquery is pre-filtered by namespace.
🧹 Nitpick comments (12)
openmeter/ledger/transactions/template.go (1)
14-14: 💤 Low valueConsider adding a comment to document the
code()method's purpose.The method name alone doesn't fully convey what kind of code this returns or how it's used. A brief comment would help future readers understand the contract.
📝 Suggested documentation
type ( guard bool // private type guard TransactionTemplate interface { typeGuard() guard + // code returns the unique template code identifying this transaction type code() TransactionTemplateCode Validate() error } )🤖 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/transactions/template.go` at line 14, Add a doc comment above the interface method declaration for code() describing what the returned TransactionTemplateCode represents and how callers should use it; specifically state the semantic meaning of TransactionTemplateCode (e.g., whether it is an identifier, enum-like constant, or template body), any invariants or expected formats, and examples of typical consumers (e.g., used to select templates or render transactions) to clarify the contract of the code() method.openmeter/ledger/impact_test.go (1)
294-294: ⚡ Quick winPrefer
InexactFloat64()for decimal assertions.Per coding guidelines, when comparing
alpacadecimal.Decimalvalues in tests, userequire.Equal(t, expectedFloat64, actual.InexactFloat64())instead ofrequire.True(t, expected.Equal(actual))for clearer failure messages.As per coding guidelines: "When asserting alpacadecimal.Decimal equality in Go tests, prefer require.Equal(t, expectedFloat64, actual.InexactFloat64()) over boolean assertions like require.True(t, expected.Equal(actual))"
Suggested fix
- require.True(t, tt.want.Equal(ledger.TransactionImpact(tx, tt.filter))) + require.Equal(t, tt.want.InexactFloat64(), ledger.TransactionImpact(tx, tt.filter).InexactFloat64())🤖 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/impact_test.go` at line 294, The test currently uses a boolean assertion comparing alpacadecimal.Decimal via tt.want.Equal(ledger.TransactionImpact(tx, tt.filter)); update this to use InexactFloat64 for clearer failures: call InexactFloat64() on both the expected (tt.want) and the actual result from ledger.TransactionImpact(tx, tt.filter) and use require.Equal to compare the float64s. Ensure you reference the same symbols (tt.want and ledger.TransactionImpact(tx, tt.filter)) so the assertion becomes require.Equal(t, tt.want.InexactFloat64(), ledger.TransactionImpact(tx, tt.filter).InexactFloat64()).openmeter/ledger/annotations_test.go (1)
9-17: ⚡ Quick winConsider adding test coverage for error cases.
This test only covers the happy path where annotations successfully round-trip to a template code. To make the test suite more comprehensive, consider adding test cases for:
- Invalid or malformed annotations
- Missing required annotation fields
- Any edge cases that
TransactionTemplateCodeFromAnnotationsshould handle🤖 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/annotations_test.go` around lines 9 - 17, Add negative test cases to cover error paths for TransactionTemplateCodeFromAnnotations: create annotations missing required fields (e.g., omit template code key), create malformed/invalid annotation payloads (bad types or corrupt values), and invalid direction values passed to TransactionAnnotations; then call TransactionTemplateCodeFromAnnotations and assert it returns a non-nil error for each case. Reference the existing TestTransactionTemplateCodeAnnotations flow and use TransactionAnnotations and TransactionTemplateCodeFromAnnotations to construct inputs and verify error behavior.openmeter/ledger/customerbalance/transactions_test.go (1)
56-56: ⚡ Quick winUse the standard decimal assertion style in tests.
Tiny tweak: prefer comparing
InexactFloat64()instead of booleanEqual(...)to match repo-wide test conventions.Suggested change
- require.True(t, item.Amount.Equal(alpacadecimal.NewFromInt(-15))) + require.Equal(t, -15.0, item.Amount.InexactFloat64())As per coding guidelines, "When asserting
alpacadecimal.Decimalequality in Go tests, preferrequire.Equal(t, expectedFloat64, actual.InexactFloat64())over boolean assertions likerequire.True(t, expected.Equal(actual))."🤖 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/customerbalance/transactions_test.go` at line 56, Replace the boolean decimal equality check that uses item.Amount.Equal(alpacadecimal.NewFromInt(-15)) with the repository-standard assertion style: call item.Amount.InexactFloat64() and assert it equals the expected float via require.Equal(t, -15.0, item.Amount.InexactFloat64()). Update the assertion that currently reads require.True(t, item.Amount.Equal(alpacadecimal.NewFromInt(-15))) to use require.Equal with the float value; keep references to item.Amount, alpacadecimal.NewFromInt only for locating the original code.openmeter/ledger/customerbalance/facade_test.go (2)
194-218: ⚡ Quick winPrefer direct numeric equality assertions for decimals in tests.
These assertions currently use boolean
Decimal.Equal(...), which gives weaker diffs on failure. Please userequire.Equal(t, expectedFloat64, actual.InexactFloat64())for consistency and clearer failures.Suggested patch
- require.True(t, balanceBeforeExpiry.Equal(amount), "balance before expiry: %s", balanceBeforeExpiry) + require.Equal(t, amount.InexactFloat64(), balanceBeforeExpiry.InexactFloat64(), "balance before expiry: %s", balanceBeforeExpiry) @@ - require.True(t, balanceAtExpiry.Equal(alpacadecimal.Zero), "balance at expiry: %s", balanceAtExpiry) + require.Equal(t, alpacadecimal.Zero.InexactFloat64(), balanceAtExpiry.InexactFloat64(), "balance at expiry: %s", balanceAtExpiry) @@ - require.True(t, currentBeforeExpiry.Equal(amount), "current balance before expiry: %s", currentBeforeExpiry) + require.Equal(t, amount.InexactFloat64(), currentBeforeExpiry.InexactFloat64(), "current balance before expiry: %s", currentBeforeExpiry) @@ - require.True(t, currentAtExpiry.Equal(alpacadecimal.Zero), "current balance at expiry: %s", currentAtExpiry) + require.Equal(t, alpacadecimal.Zero.InexactFloat64(), currentAtExpiry.InexactFloat64(), "current balance at expiry: %s", currentAtExpiry) @@ - require.True(t, balanceAtFirstBooking.Equal(alpacadecimal.NewFromInt(100)), "balance as of first booking: %s", balanceAtFirstBooking) + require.Equal(t, 100.0, balanceAtFirstBooking.InexactFloat64(), "balance as of first booking: %s", balanceAtFirstBooking) @@ - require.True(t, currentBalance.Equal(alpacadecimal.NewFromInt(120))) + require.Equal(t, 120.0, currentBalance.InexactFloat64())As per coding guidelines "When asserting
alpacadecimal.Decimalequality in Go tests, preferrequire.Equal(t, expectedFloat64, actual.InexactFloat64())over boolean assertions likerequire.True(t, expected.Equal(actual))".Also applies to: 245-252
🤖 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/customerbalance/facade_test.go` around lines 194 - 218, Replace boolean Decimal.Equal assertions with numeric equality assertions using InexactFloat64: for each require.True(t, X.Equal(Y), ...) (e.g. the assertions around balanceBeforeExpiry, balanceAtExpiry, currentBeforeExpiry, currentAtExpiry that follow calls to facade.GetBalance and clock.FreezeTime), change to require.Equal(t, expectedFloat64, actual.InexactFloat64()) — where expectedFloat64 is either amount.InexactFloat64() for comparisons to the variable amount or 0.0 for comparisons to alpacadecimal.Zero; apply the same change to the other occurrences mentioned (around lines 245-252) so tests use require.Equal with InexactFloat64 for clearer diffs.
154-156: ⚡ Quick winUse
clock.SetTimefor later jumps after the first freeze.You freeze once at Line 154 with a matching deferred unfreeze, but Lines 204 and 212 freeze again without local unfreeze pairing. Switching those follow-up calls to
clock.SetTime(...)keeps behavior deterministic and avoids freeze-state leakage risks.Suggested patch
clock.FreezeTime(issuedAt) defer clock.UnFreeze() defer clock.ResetTime() @@ - clock.FreezeTime(beforeExpiry) + clock.SetTime(beforeExpiry) currentBeforeExpiry, err := facade.GetBalance(t.Context(), GetBalanceInput{ @@ - clock.FreezeTime(expiresAt) + clock.SetTime(expiresAt) currentAtExpiry, err := facade.GetBalance(t.Context(), GetBalanceInput{As per coding guidelines "When using
clock.FreezeTime(...)in Go tests, immediately pair it withdefer clock.UnFreeze()in the same scope to prevent later assertions or subtests from inheriting frozen time".Also applies to: 204-212
🤖 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/customerbalance/facade_test.go` around lines 154 - 156, The test currently calls clock.FreezeTime(issuedAt) with a deferred clock.UnFreeze(), but later test code re-freezes time again (uses clock.FreezeTime at the later assertions) without pairing those freezes with immediate defers, risking frozen-time leakage; replace those subsequent clock.FreezeTime(...) calls with clock.SetTime(...) so you move time deterministically without creating additional freeze state, keeping the original clock.FreezeTime(issuedAt)/defer clock.UnFreeze() pairing intact and referencing the same clock helper used in facade_test.go.openmeter/ledger/routingrules/routingrules_test.go (1)
131-161: ⚡ Quick winAdd the complementary negative case for duplicate identity keys.
Nice coverage for “duplicate sub-account + unique identities”. It’d be great to also assert the same setup fails when both entries share the same
IdentityKeyValue, so the uniqueness contract is locked in both directions.As per coding guidelines "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/routingrules/routingrules_test.go` around lines 131 - 161, Add a complementary negative test that mirrors TestDefaultValidator_AllowsDuplicateSubAccountEntriesWithUniqueIdentities but sets the two entries on the same accruedAddress to have the same IdentityKeyValue (e.g. "source:0") and asserts validator.ValidateEntries returns an error; locate the test harness using routingrules.DefaultValidator, the ValidateEntries call, and transactionstestutils.AnyEntryInput to replicate the setup and only change the IdentityKeyValue to confirm duplicates are rejected.openmeter/ledger/customerbalance/expired_loader_test.go (2)
225-227: ⚡ Quick winPlease pair each
clock.FreezeTime(...)with an immediate unfreeze in the same scope.Right now freeze/unfreeze relies on higher-level cleanup, which makes helpers easier to leak frozen time from if reused.
As per coding guidelines "When using
clock.FreezeTime(...)in Go tests, immediately pair it withdefer clock.UnFreeze()in the same scope to prevent later assertions or subtests from inheriting frozen time".Also applies to: 258-260, 277-279, 308-309, 317-318
🤖 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/customerbalance/expired_loader_test.go` around lines 225 - 227, Each call to clock.FreezeTime(...) must be immediately paired with defer clock.UnFreeze() in the same scope to avoid leaking frozen time; update the test so that after each clock.FreezeTime(issuedAt) (and the other FreezeTime occurrences around e.bookFBOBalance, e.fundOpenReceivable, and the locations noted at 258-260, 277-279, 308-309, 317-318) you add a matching defer clock.UnFreeze() before calling helpers like e.bookFBOBalance, e.fundOpenReceivable or any subsequent assertions, ensuring the freeze/unfreeze are colocated in the same function/block.
426-428: ⚡ Quick winUse the repo’s preferred decimal assertion style here.
These
require.True(expected.Equal(actual))checks should userequire.Equal(..., actual.InexactFloat64())for consistency across tests.As per coding guidelines "When asserting
alpacadecimal.Decimalequality in Go tests, preferrequire.Equal(t, expectedFloat64, actual.InexactFloat64())over boolean assertions likerequire.True(t, expected.Equal(actual))".Also applies to: 446-448
🤖 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/customerbalance/expired_loader_test.go` around lines 426 - 428, Replace the boolean decimal equality assertions with the repo-preferred float equality style: for each check that currently does require.True(alpacadecimal.NewFromInt(expectedItem.X).Equal(item.Y)) (for X = amount, balanceBefore, balanceAfter and Y = Amount, Balance.Before, Balance.After), call alpacadecimal.NewFromInt(expectedItem.X).InexactFloat64() as the expected value and assert with require.Equal(t, expectedFloat64, item.Y.InexactFloat64(), ...) instead; update the three assertions shown and the analogous assertions at lines 446-448 accordingly so all alpacadecimal comparisons use require.Equal with InexactFloat64().openmeter/ledger/chargeadapter/creditpurchase_test.go (1)
108-109: ⚡ Quick winPlease switch these decimal equality checks to the preferred assertion form.
Use
require.Equal(t, expectedFloat64, actual.InexactFloat64())instead of booleanrequire.True(decimal.Equal(...))for consistency and clearer failures.As per coding guidelines: “When asserting
alpacadecimal.Decimalequality in Go tests, preferrequire.Equal(t, expectedFloat64, actual.InexactFloat64())over boolean assertions likerequire.True(t, expected.Equal(actual)).”Also applies to: 113-117, 146-147, 151-155
🤖 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/chargeadapter/creditpurchase_test.go` around lines 108 - 109, Replace the boolean decimal equality assertions with the preferred float equality form: for each assertion that uses require.True(... Equal(...)) (e.g., checks on rows[0].Amount, rows[0].ExpiresAt and other occurrences mentioned), call require.Equal(t, expectedFloat64, actualDecimal.InexactFloat64()) instead; compute the expected value as a float64 (e.g., 100 -> 100.0 or expiresAt converted appropriately) and invoke actual.InexactFloat64() on the alpacadecimal.Decimal instance (rows[0].Amount.InexactFloat64(), rows[0].ExpiresAt.InexactFloat64(), etc.) so failures show clearer diffs and match the coding guideline.openmeter/ledger/collector/collection_fbo_test.go (1)
32-34: ⚡ Quick winUse the repo-preferred decimal assertion style in these tests.
These assertions currently use
require.True(...Equal(...)); please switch torequire.Equal(t, expectedFloat64, actual.InexactFloat64())for consistency and better failure output.As per coding guidelines: “When asserting
alpacadecimal.Decimalequality in Go tests, preferrequire.Equal(t, expectedFloat64, actual.InexactFloat64())over boolean assertions likerequire.True(t, expected.Equal(actual)).”Also applies to: 71-72, 78-79, 106-107, 117-118
🤖 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/collection_fbo_test.go` around lines 32 - 34, Replace boolean Decimal equality assertions that use require.True(...Equal(...)) with the repo-preferred assertion style require.Equal(t, expectedFloat64, actual.InexactFloat64()): for example change the checks that compare alpacadecimal.NewFromInt(30).Equal(sources[0].Amount) and alpacadecimal.NewFromInt(30).Equal(sources[1].Amount) to require.Equal(t, 30.0, sources[0].Amount.InexactFloat64()) and require.Equal(t, 30.0, sources[1].Amount.InexactFloat64()); apply the same replacement pattern to the other occurrences mentioned (around the assertions involving sources, priorityTwo.Address().SubAccountID() comparisons and the lines at 71-72, 78-79, 106-107, 117-118) so tests use InexactFloat64() for actual Decimal values and a plain float64 literal for expected values.openmeter/ledger/collector/correct.go (1)
444-489: 💤 Low valueMinor observation: release ordering isn't explicit here.
The breakage releases are consumed in the order returned by
ListReleases. If there's a specific ordering requirement (e.g., LIFO for reversing the most recent backfill first), the caller or adapter should ensure that ordering. IfListReleasesalready provides deterministic ordering, this is fine as-is.🤖 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/correct.go` around lines 444 - 489, The function resolveAdvanceBackfillBreakageReopenInputs currently consumes breakage releases in whatever order ListReleases returns; make the ordering explicit to ensure deterministic/LIFO behavior by sorting the releases slice before the consumption loop. After obtaining releases from c.breakage.ListReleases, apply a deterministic sort (e.g., sort.Slice on releases) using a clear comparator such as release.CreatedAt descending for LIFO (or release.ID if CreatedAt is unavailable), then proceed with the existing loop using release.OpenAmount and ReopenRelease; this guarantees the intended order regardless of ListReleases' return order.
🤖 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/billing/charges/creditpurchase/adapter/funded_credit_activity_test.go`:
- Line 317: Replace the standalone background context with the test harness
context: in funded_credit_activity_test.go where ctx is set (currently using
context.Background()), change it to use the suite's test context via
s.T().Context() so the test's cancellation/lifecycle controls propagate (i.e.,
replace creation of ctx with s.T().Context() in the test that declares ctx).
In `@openmeter/ent/schema/ledger_entry.go`:
- Around line 33-35: The migration adds field.String("identity_key") with
Default("") and then a UNIQUE index on (transaction_id, sub_account_id,
identity_key), which will fail if existing rows share (transaction_id,
sub_account_id) because identity_key will be empty for all; before applying,
scan existing data for duplicate (transaction_id, sub_account_id) pairs and
either (a) backfill a non-empty unique value per duplicate group (e.g., assign
UUIDs or sequential IDs) so each row gets a distinct identity_key, or (b) alter
the migration to populate identity_key during the schema change (or skip adding
the UNIQUE index) to ensure CREATE UNIQUE INDEX succeeds; look for
field.String("identity_key") and the code that creates the unique index on
(transaction_id, sub_account_id, identity_key) to implement the chosen backfill
or validation strategy.
In `@openmeter/ledger/breakage/adapter/record.go`:
- Around line 98-101: ListReleaseRecords is currently OR-ing a global
KindEQ(ledger.BreakageKindReopen) which pulls all reopen rows for the customer;
change the predicate so reopen rows are constrained by the same source filters
as releases. Replace the
dbledgerbreakagerecord.Or(dbledgerbreakagerecord.And(releasePredicates...),
dbledgerbreakagerecord.KindEQ(ledger.BreakageKindReopen)) expression with a
predicate that requires KindEQ(ledger.BreakageKindReopen) AND the same
releasePredicates (e.g. build reopenPredicates by copying releasePredicates
minus any existing Kind predicate and appending
dbledgerbreakagerecord.KindEQ(ledger.BreakageKindReopen), or construct
dbledgerbreakagerecord.And(append(releasePredicates,
dbledgerbreakagerecord.KindEQ(ledger.BreakageKindReopen))...)) so only matching
reopen rows are returned.
In `@openmeter/ledger/breakage/service.go`:
- Around line 698-735: The function breakageKindForTemplate currently panics on
unknown template types; change its signature to return (ledger.BreakageKind,
error) and return a descriptive error for unsupported template kinds instead of
calling panic, then update resolveBreakageTemplate to call the new
breakageKindForTemplate, check the error, and propagate it (returning it) before
calling transactions.WithAnnotations; reference the symbols
breakageKindForTemplate and resolveBreakageTemplate and ensure any callers are
updated to handle the (kind, error) return.
- Around line 162-195: ReleasePlanInput.Validate currently allows SourceKind
values like SourceKindUsage / SourceKindUsageCorrection /
SourceKindCreditPurchaseCorrection / SourceKindAdvanceBackfill while leaving
SourceEntryIdentityKey empty, which breaks later source-linked lookups; update
ReleasePlanInput.Validate (the function named ReleasePlanInput.Validate) to
require a non-empty SourceEntryIdentityKey when i.SourceKind is one of those
source-linked kinds (append an error like "source entry identity is required for
source-linked releases" to errs if the field is empty), keeping the existing
invalid-kind default branch intact.
In `@openmeter/ledger/chargeadapter/creditpurchase.go`:
- Around line 43-45: Replace the panic check for transactionManager with an
explicit error return from the constructor that contains this code (the
constructor in creditpurchase.go that currently checks transactionManager).
Change the function signature to return (T, error) instead of panicking, return
a descriptive error when transactionManager == nil, and update callers to handle
the error (or validate at wiring time) so no runtime panic is possible; keep the
error message descriptive and reference transactionManager in the returned
error.
In `@openmeter/ledger/chargeadapter/usagebased.go`:
- Around line 247-248: The SourceBalanceAsOf timestamp is using clock.Now()
while BookedAt uses input.AllocateAt, causing non-determinism on
delayed/replayed runs; update the construction that sets BookedAt:
input.AllocateAt and SourceBalanceAsOf: clock.Now() (in the allocation/charge
creation code around the UsageBased charge builder) to use the same as-of time
by assigning SourceBalanceAsOf: input.AllocateAt so the collection boundary
matches the booking time.
In `@openmeter/ledger/collector/collection_fbo.go`:
- Around line 106-117: Add a nil guard for c.deps.AccountService before it is
used: check if c.deps.AccountService == nil and return a descriptive error
(e.g., "account service is required") just like the existing checks for
AccountCatalog and BalanceQuerier, then call
c.deps.AccountService.GetCustomerAccounts(ctx, customerID); this prevents a nil
dereference when invoking GetCustomerAccounts on AccountService.
In `@openmeter/ledger/collector/service.go`:
- Around line 64-67: Change NewService to return (Service, error) instead of
panicking: update the signature of NewService to return (Service, error), remove
the panic("collector transaction manager is required") check and replace it with
a nil-TransactionManager validation that returns a descriptive error (e.g.,
fmt.Errorf) when config.TransactionManager is nil, and otherwise return the
constructed Service and nil error; then update all call sites (notably the
callers in app/common/charges.go and affected test files) to handle the returned
error similarly to other constructors in this package (e.g.,
breakage.NewService, recognizer.NewService).
In `@openmeter/ledger/transactions/codes.go`:
- Around line 110-114: The TemplateCode function currently panics when
templateCode returns an error; change TemplateCode to return (string, error)
instead of panicking so failures are propagated to callers (update its signature
and replace panic(err) with return "", err, and return the computed code on
success). Update all callers of TemplateCode to handle the error (or add a
separate MustTemplateCode helper for test-only use that panics). Make sure to
keep the underlying templateCode(...) call and error values unchanged so the
exact error is returned.
In
`@tools/migrate/migrations/20260511211059_add_credit_expiration_breakage.up.sql`:
- Around line 30-31: The migration creates a redundant unique index on the
primary key; remove the CREATE UNIQUE INDEX "ledgerbreakagerecord_id" ON
"ledger_breakage_records" ("id"); statement so the migration only relies on the
existing PRIMARY KEY on "id" and avoids creating the duplicate index.
---
Outside diff comments:
In `@openmeter/ledger/customerbalance/transactions.go`:
- Around line 137-145: The running-balance computation is using the current time
while transactions were loaded with a cutoff via
creditTransactionsAsOf(input.AsOf), causing incorrect per-item
Balance.Before/After for historical queries; update the running-balance query
call to accept and use the same cutoff by passing
creditTransactionsAsOf(input.AsOf) (or the AsOf value stored on loaderInput)
into the balance calculation routine so the balance query uses the identical
AsOf cutoff as creditTransactionLoaderInput and produces correct
Balance.Before/After values.
In `@openmeter/ledger/historical/adapter/ledger.go`:
- Around line 476-534: The HAVING SUM(amount) subquery in
scopedFBOMovementTransactionSelector is currently unscoped by namespace causing
cross-tenant aggregation; modify the predicate chain to restrict the selector by
namespace before GroupBy. Add a namespace parameter (e.g. namespace string) to
scopedFBOMovementTransactionSelector and propagate it from
ledgerTransactionCreditMovementPredicate, then apply a Where filter on the
appropriate table column (e.g. entries.C(ledgerentrydb.FieldNamespace) or
accounts.C(ledgeraccountdb.FieldNamespace) depending on your schema) so the
JOIN/WHERE that narrows to customer_fbo and accountIDs runs inside the grouped
subquery rather than only in the outer query. Ensure the new namespace argument
is used wherever scopedFBOMovementTransactionSelector is called so the subquery
is pre-filtered by namespace.
---
Nitpick comments:
In `@openmeter/ledger/annotations_test.go`:
- Around line 9-17: Add negative test cases to cover error paths for
TransactionTemplateCodeFromAnnotations: create annotations missing required
fields (e.g., omit template code key), create malformed/invalid annotation
payloads (bad types or corrupt values), and invalid direction values passed to
TransactionAnnotations; then call TransactionTemplateCodeFromAnnotations and
assert it returns a non-nil error for each case. Reference the existing
TestTransactionTemplateCodeAnnotations flow and use TransactionAnnotations and
TransactionTemplateCodeFromAnnotations to construct inputs and verify error
behavior.
In `@openmeter/ledger/chargeadapter/creditpurchase_test.go`:
- Around line 108-109: Replace the boolean decimal equality assertions with the
preferred float equality form: for each assertion that uses require.True(...
Equal(...)) (e.g., checks on rows[0].Amount, rows[0].ExpiresAt and other
occurrences mentioned), call require.Equal(t, expectedFloat64,
actualDecimal.InexactFloat64()) instead; compute the expected value as a float64
(e.g., 100 -> 100.0 or expiresAt converted appropriately) and invoke
actual.InexactFloat64() on the alpacadecimal.Decimal instance
(rows[0].Amount.InexactFloat64(), rows[0].ExpiresAt.InexactFloat64(), etc.) so
failures show clearer diffs and match the coding guideline.
In `@openmeter/ledger/collector/collection_fbo_test.go`:
- Around line 32-34: Replace boolean Decimal equality assertions that use
require.True(...Equal(...)) with the repo-preferred assertion style
require.Equal(t, expectedFloat64, actual.InexactFloat64()): for example change
the checks that compare alpacadecimal.NewFromInt(30).Equal(sources[0].Amount)
and alpacadecimal.NewFromInt(30).Equal(sources[1].Amount) to require.Equal(t,
30.0, sources[0].Amount.InexactFloat64()) and require.Equal(t, 30.0,
sources[1].Amount.InexactFloat64()); apply the same replacement pattern to the
other occurrences mentioned (around the assertions involving sources,
priorityTwo.Address().SubAccountID() comparisons and the lines at 71-72, 78-79,
106-107, 117-118) so tests use InexactFloat64() for actual Decimal values and a
plain float64 literal for expected values.
In `@openmeter/ledger/collector/correct.go`:
- Around line 444-489: The function resolveAdvanceBackfillBreakageReopenInputs
currently consumes breakage releases in whatever order ListReleases returns;
make the ordering explicit to ensure deterministic/LIFO behavior by sorting the
releases slice before the consumption loop. After obtaining releases from
c.breakage.ListReleases, apply a deterministic sort (e.g., sort.Slice on
releases) using a clear comparator such as release.CreatedAt descending for LIFO
(or release.ID if CreatedAt is unavailable), then proceed with the existing loop
using release.OpenAmount and ReopenRelease; this guarantees the intended order
regardless of ListReleases' return order.
In `@openmeter/ledger/customerbalance/expired_loader_test.go`:
- Around line 225-227: Each call to clock.FreezeTime(...) must be immediately
paired with defer clock.UnFreeze() in the same scope to avoid leaking frozen
time; update the test so that after each clock.FreezeTime(issuedAt) (and the
other FreezeTime occurrences around e.bookFBOBalance, e.fundOpenReceivable, and
the locations noted at 258-260, 277-279, 308-309, 317-318) you add a matching
defer clock.UnFreeze() before calling helpers like e.bookFBOBalance,
e.fundOpenReceivable or any subsequent assertions, ensuring the freeze/unfreeze
are colocated in the same function/block.
- Around line 426-428: Replace the boolean decimal equality assertions with the
repo-preferred float equality style: for each check that currently does
require.True(alpacadecimal.NewFromInt(expectedItem.X).Equal(item.Y)) (for X =
amount, balanceBefore, balanceAfter and Y = Amount, Balance.Before,
Balance.After), call alpacadecimal.NewFromInt(expectedItem.X).InexactFloat64()
as the expected value and assert with require.Equal(t, expectedFloat64,
item.Y.InexactFloat64(), ...) instead; update the three assertions shown and the
analogous assertions at lines 446-448 accordingly so all alpacadecimal
comparisons use require.Equal with InexactFloat64().
In `@openmeter/ledger/customerbalance/facade_test.go`:
- Around line 194-218: Replace boolean Decimal.Equal assertions with numeric
equality assertions using InexactFloat64: for each require.True(t, X.Equal(Y),
...) (e.g. the assertions around balanceBeforeExpiry, balanceAtExpiry,
currentBeforeExpiry, currentAtExpiry that follow calls to facade.GetBalance and
clock.FreezeTime), change to require.Equal(t, expectedFloat64,
actual.InexactFloat64()) — where expectedFloat64 is either
amount.InexactFloat64() for comparisons to the variable amount or 0.0 for
comparisons to alpacadecimal.Zero; apply the same change to the other
occurrences mentioned (around lines 245-252) so tests use require.Equal with
InexactFloat64 for clearer diffs.
- Around line 154-156: The test currently calls clock.FreezeTime(issuedAt) with
a deferred clock.UnFreeze(), but later test code re-freezes time again (uses
clock.FreezeTime at the later assertions) without pairing those freezes with
immediate defers, risking frozen-time leakage; replace those subsequent
clock.FreezeTime(...) calls with clock.SetTime(...) so you move time
deterministically without creating additional freeze state, keeping the original
clock.FreezeTime(issuedAt)/defer clock.UnFreeze() pairing intact and referencing
the same clock helper used in facade_test.go.
In `@openmeter/ledger/customerbalance/transactions_test.go`:
- Line 56: Replace the boolean decimal equality check that uses
item.Amount.Equal(alpacadecimal.NewFromInt(-15)) with the repository-standard
assertion style: call item.Amount.InexactFloat64() and assert it equals the
expected float via require.Equal(t, -15.0, item.Amount.InexactFloat64()). Update
the assertion that currently reads require.True(t,
item.Amount.Equal(alpacadecimal.NewFromInt(-15))) to use require.Equal with the
float value; keep references to item.Amount, alpacadecimal.NewFromInt only for
locating the original code.
In `@openmeter/ledger/impact_test.go`:
- Line 294: The test currently uses a boolean assertion comparing
alpacadecimal.Decimal via tt.want.Equal(ledger.TransactionImpact(tx,
tt.filter)); update this to use InexactFloat64 for clearer failures: call
InexactFloat64() on both the expected (tt.want) and the actual result from
ledger.TransactionImpact(tx, tt.filter) and use require.Equal to compare the
float64s. Ensure you reference the same symbols (tt.want and
ledger.TransactionImpact(tx, tt.filter)) so the assertion becomes
require.Equal(t, tt.want.InexactFloat64(), ledger.TransactionImpact(tx,
tt.filter).InexactFloat64()).
In `@openmeter/ledger/routingrules/routingrules_test.go`:
- Around line 131-161: Add a complementary negative test that mirrors
TestDefaultValidator_AllowsDuplicateSubAccountEntriesWithUniqueIdentities but
sets the two entries on the same accruedAddress to have the same
IdentityKeyValue (e.g. "source:0") and asserts validator.ValidateEntries returns
an error; locate the test harness using routingrules.DefaultValidator, the
ValidateEntries call, and transactionstestutils.AnyEntryInput to replicate the
setup and only change the IdentityKeyValue to confirm duplicates are rejected.
In `@openmeter/ledger/transactions/template.go`:
- Line 14: Add a doc comment above the interface method declaration for code()
describing what the returned TransactionTemplateCode represents and how callers
should use it; specifically state the semantic meaning of
TransactionTemplateCode (e.g., whether it is an identifier, enum-like constant,
or template body), any invariants or expected formats, and examples of typical
consumers (e.g., used to select templates or render transactions) to clarify the
contract of the code() method.
🪄 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: 7e92eec2-7ce3-4031-82d2-e6ba901ce222
⛔ Files ignored due to path filters (32)
api/v3/openapi.yamlis excluded by!**/openapi.yamlgo.sumis excluded by!**/*.sum,!**/*.sumopenmeter/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/client.gois excluded by!**/ent/db/**openmeter/ent/db/cursor.gois excluded by!**/ent/db/**openmeter/ent/db/ent.gois excluded by!**/ent/db/**openmeter/ent/db/entmixinaccessor.gois excluded by!**/ent/db/**openmeter/ent/db/expose.gois excluded by!**/ent/db/**openmeter/ent/db/hook/hook.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord/ledgerbreakagerecord.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord/where.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_create.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_delete.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_query.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_update.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry/ledgerentry.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry/where.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry_create.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/paginate.gois excluded by!**/ent/db/**openmeter/ent/db/predicate/predicate.gois excluded by!**/ent/db/**openmeter/ent/db/runtime.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**openmeter/ent/db/tx.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (115)
.agents/skills/ledger/SKILL.mdapi/spec/packages/aip/src/customers/credits/grant.tspapi/spec/packages/aip/src/customers/credits/ledger.tspapi/spec/packages/aip/src/customers/credits/operations.tspapi/v3/api.gen.goapi/v3/filters/parse.goapi/v3/filters/parse_test.goapi/v3/handlers/customers/credits/convert.goapi/v3/handlers/customers/credits/get_balance.goapi/v3/handlers/customers/credits/list_transactions_test.goapp/common/billing.goapp/common/charges.goapp/common/customerbalance.gocmd/billing-worker/wire_gen.gocmd/jobs/internal/wire_gen.gocmd/server/wire_gen.goopenmeter/billing/charges/creditpurchase/adapter/charge.goopenmeter/billing/charges/creditpurchase/adapter/funded_credit_activity.goopenmeter/billing/charges/creditpurchase/adapter/funded_credit_activity_test.goopenmeter/billing/charges/creditpurchase/adapter/mapper.goopenmeter/billing/charges/creditpurchase/charge.goopenmeter/billing/charges/creditpurchase/funded_credit_activity.goopenmeter/billing/charges/creditpurchase/service/promotional.goopenmeter/billing/creditgrant/service.goopenmeter/billing/creditgrant/service/service.goopenmeter/ent/schema/chargescreditpurchase.goopenmeter/ent/schema/ledger_breakage_record.goopenmeter/ent/schema/ledger_entry.goopenmeter/ledger/account.goopenmeter/ledger/account/account.goopenmeter/ledger/annotations.goopenmeter/ledger/annotations_test.goopenmeter/ledger/balance.goopenmeter/ledger/breakage/README.mdopenmeter/ledger/breakage/adapter/adapter.goopenmeter/ledger/breakage/adapter/record.goopenmeter/ledger/breakage/breakage_impacts.goopenmeter/ledger/breakage/noop.goopenmeter/ledger/breakage/service.goopenmeter/ledger/breakage/types.goopenmeter/ledger/chargeadapter/creditpurchase.goopenmeter/ledger/chargeadapter/creditpurchase_test.goopenmeter/ledger/chargeadapter/flatfee.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/helpers.goopenmeter/ledger/chargeadapter/usagebased.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/collector/README.mdopenmeter/ledger/collector/collect.goopenmeter/ledger/collector/collection_fbo.goopenmeter/ledger/collector/collection_fbo_test.goopenmeter/ledger/collector/correct.goopenmeter/ledger/collector/service.goopenmeter/ledger/customerbalance/README.mdopenmeter/ledger/customerbalance/expired_loader.goopenmeter/ledger/customerbalance/expired_loader_test.goopenmeter/ledger/customerbalance/facade.goopenmeter/ledger/customerbalance/facade_test.goopenmeter/ledger/customerbalance/funded_loader.goopenmeter/ledger/customerbalance/ledger_loader.goopenmeter/ledger/customerbalance/loaders.goopenmeter/ledger/customerbalance/noop.goopenmeter/ledger/customerbalance/service.goopenmeter/ledger/customerbalance/service_test.goopenmeter/ledger/customerbalance/testenv_test.goopenmeter/ledger/customerbalance/transactions.goopenmeter/ledger/customerbalance/transactions_test.goopenmeter/ledger/historical/adapter/ledger.goopenmeter/ledger/historical/adapter/ledger_test.goopenmeter/ledger/historical/adapter/sumentries_query.goopenmeter/ledger/historical/balance.goopenmeter/ledger/historical/entry.goopenmeter/ledger/impact.goopenmeter/ledger/impact_test.goopenmeter/ledger/ledger_test.goopenmeter/ledger/noop/noop.goopenmeter/ledger/primitives.goopenmeter/ledger/query.goopenmeter/ledger/resolvers/account.goopenmeter/ledger/routingrules/defaults.goopenmeter/ledger/routingrules/routingrules.goopenmeter/ledger/routingrules/routingrules_test.goopenmeter/ledger/testutils/integration.goopenmeter/ledger/transactions/accrual.goopenmeter/ledger/transactions/accrual_test.goopenmeter/ledger/transactions/breakage.goopenmeter/ledger/transactions/codes.goopenmeter/ledger/transactions/collection.goopenmeter/ledger/transactions/correction.goopenmeter/ledger/transactions/correction_leg.goopenmeter/ledger/transactions/correction_test.goopenmeter/ledger/transactions/customer.goopenmeter/ledger/transactions/earnings.goopenmeter/ledger/transactions/earnings_test.goopenmeter/ledger/transactions/entry_identity.goopenmeter/ledger/transactions/fx.goopenmeter/ledger/transactions/input.goopenmeter/ledger/transactions/legacy.goopenmeter/ledger/transactions/resolve.goopenmeter/ledger/transactions/resolve_test.goopenmeter/ledger/transactions/template.goopenmeter/ledger/transactions/testutils/anytransaction.gopkg/cmpx/compare.gotest/app/stripe/invoice_test.gotest/credits/base.gotest/credits/creditgrant_test.gotest/credits/sanity_test.gotools/migrate/migrations/20260511134625_ledger_transaction_template_codes.down.sqltools/migrate/migrations/20260511134625_ledger_transaction_template_codes.up.sqltools/migrate/migrations/20260511211059_add_credit_expiration_breakage.down.sqltools/migrate/migrations/20260511211059_add_credit_expiration_breakage.up.sqltools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.down.sqltools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.up.sqltools/migrate/migrations/20260514154312_add_breakage_source_entry_id.down.sqltools/migrate/migrations/20260514154312_add_breakage_source_entry_id.up.sql
| } | ||
|
|
||
| func (s *ListFundedCreditActivitiesSuite) TestFiltersByAsOf() { | ||
| ctx := context.Background() |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
cat -n openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity_test.go | sed -n '310,330p'Repository: openmeterio/openmeter
Length of output: 729
🏁 Script executed:
cat -n openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity_test.go | head -50Repository: openmeterio/openmeter
Length of output: 1761
Use s.T().Context() instead of context.Background().
Line 317 should grab the context from the test harness so cancellation and lifecycle stay tied to the test's lifecycle.
Suggested patch
func (s *ListFundedCreditActivitiesSuite) TestFiltersByAsOf() {
- ctx := context.Background()
+ ctx := s.T().Context()
ns := "test-funded-activity-as-of"
customerID := s.createCustomer(ns)📝 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.
| ctx := context.Background() | |
| ctx := s.T().Context() |
🤖 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/adapter/funded_credit_activity_test.go`
at line 317, Replace the standalone background context with the test harness
context: in funded_credit_activity_test.go where ctx is set (currently using
context.Background()), change it to use the suite's test context via
s.T().Context() so the test's cancellation/lifecycle controls propagate (i.e.,
replace creation of ctx with s.T().Context() in the test that declares ctx).
| field.String("identity_key"). | ||
| Default(""). | ||
| Immutable(), |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check if the corresponding up migration handles existing data
# Find the matching up migration
up_migration="tools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.up.sql"
if [ -f "$up_migration" ]; then
echo "=== Checking up migration for identity_key ==="
cat "$up_migration"
echo ""
echo "=== Looking for data handling (backfill, default, etc.) ==="
if grep -i "default\|update\|backfill" "$up_migration"; then
echo "Found data handling statements"
else
echo "⚠ No explicit data handling found - check if default '' is sufficient"
fi
else
echo "⚠ Up migration not found at expected path: $up_migration"
echo "Searching for it..."
fd -e sql -e up.sql . tools/migrate/migrations/ | rg identity_key
fiRepository: openmeterio/openmeter
Length of output: 676
🏁 Script executed:
cat openmeter/ent/schema/ledger_entry.goRepository: openmeterio/openmeter
Length of output: 1784
🏁 Script executed:
fd -e sql . tools/migrate/migrations/ | rg identity_keyRepository: openmeterio/openmeter
Length of output: 221
🏁 Script executed:
cat tools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.down.sqlRepository: openmeterio/openmeter
Length of output: 342
🏁 Script executed:
fd -type f -name "*.up.sql" tools/migrate/migrations/ | xargs grep -l "ledger_entries" | head -10Repository: openmeterio/openmeter
Length of output: 236
🏁 Script executed:
fd -name "*.up.sql" tools/migrate/migrations/ | xargs grep -l "ledger_entries"Repository: openmeterio/openmeter
Length of output: 298
🏁 Script executed:
fd -name "*.up.sql" tools/migrate/migrations/ | xargs grep -l "CREATE TABLE.*ledger_entries"Repository: openmeterio/openmeter
Length of output: 298
🏁 Script executed:
grep -r "ledger_entries" tools/migrate/migrations/*.up.sql | head -20Repository: openmeterio/openmeter
Length of output: 2854
🏁 Script executed:
grep -r "CREATE TABLE.*ledger_entries" tools/migrate/migrations/Repository: openmeterio/openmeter
Length of output: 151
🏁 Script executed:
git log --oneline tools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.up.sql | head -5Repository: openmeterio/openmeter
Length of output: 88
🏁 Script executed:
grep -A 30 "CREATE TABLE.*ledger_entries" tools/migrate/migrations/20260316165258_ledger.up.sql | head -40Repository: openmeterio/openmeter
Length of output: 1916
Verify existing data compatibility before migration.
Adding a unique constraint on (transaction_id, sub_account_id, identity_key) with identity_key defaulting to "" is risky. The original schema allowed multiple entries per (transaction_id, sub_account_id) pair—only non-unique indices existed before. When the migration runs, all existing entries get identity_key = "", which means any duplicate (transaction_id, sub_account_id) pairs in the data will violate the new constraint and fail the CREATE UNIQUE INDEX step.
Before deploying, validate that no existing transactions have multiple entries to the same sub-account, or update the migration to backfill identity_key with a unique value (e.g., a sequential ID or UUID) for entries that share (transaction_id, sub_account_id).
🤖 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/ent/schema/ledger_entry.go` around lines 33 - 35, The migration
adds field.String("identity_key") with Default("") and then a UNIQUE index on
(transaction_id, sub_account_id, identity_key), which will fail if existing rows
share (transaction_id, sub_account_id) because identity_key will be empty for
all; before applying, scan existing data for duplicate (transaction_id,
sub_account_id) pairs and either (a) backfill a non-empty unique value per
duplicate group (e.g., assign UUIDs or sequential IDs) so each row gets a
distinct identity_key, or (b) alter the migration to populate identity_key
during the schema change (or skip adding the UNIQUE index) to ensure CREATE
UNIQUE INDEX succeeds; look for field.String("identity_key") and the code that
creates the unique index on (transaction_id, sub_account_id, identity_key) to
implement the chosen backfill or validation strategy.
| func (i ReleasePlanInput) Validate() error { | ||
| var errs []error | ||
|
|
||
| if err := i.Plan.Record.ValidateForReference(); err != nil { | ||
| errs = append(errs, fmt.Errorf("plan: %w", err)) | ||
| } | ||
|
|
||
| if i.Plan.Kind != ledger.BreakageKindPlan { | ||
| errs = append(errs, errors.New("plan record must have kind plan")) | ||
| } | ||
|
|
||
| if err := ledger.ValidateTransactionAmount(i.Amount); err != nil { | ||
| errs = append(errs, fmt.Errorf("amount: %w", err)) | ||
| } | ||
|
|
||
| if i.Amount.GreaterThan(i.Plan.OpenAmount) { | ||
| errs = append(errs, errors.New("release amount cannot exceed open plan amount")) | ||
| } | ||
|
|
||
| if i.Plan.FBOAddress == nil { | ||
| errs = append(errs, errors.New("plan FBO address is required")) | ||
| } | ||
|
|
||
| if i.Plan.BreakageAddress == nil { | ||
| errs = append(errs, errors.New("plan breakage address is required")) | ||
| } | ||
|
|
||
| switch i.SourceKind { | ||
| case SourceKindUsage, SourceKindUsageCorrection, SourceKindCreditPurchaseCorrection, SourceKindAdvanceBackfill: | ||
| default: | ||
| errs = append(errs, fmt.Errorf("invalid release source kind: %s", i.SourceKind)) | ||
| } | ||
|
|
||
| return errors.Join(errs...) |
There was a problem hiding this comment.
Require a source identity for source-linked releases.
ReleasePlanInput.Validate() currently accepts SourceKindUsage/correction-style releases with an empty SourceEntryIdentityKey. That lets PersistCommittedRecords() write a release row without SourceEntryID, so later source-keyed lookup/reopen flows lose the linkage entirely.
💡 Suggested fix
func (i ReleasePlanInput) Validate() error {
var errs []error
@@
switch i.SourceKind {
- case SourceKindUsage, SourceKindUsageCorrection, SourceKindCreditPurchaseCorrection, SourceKindAdvanceBackfill:
+ case SourceKindUsage, SourceKindUsageCorrection, SourceKindCreditPurchaseCorrection:
+ if i.SourceEntryIdentityKey == "" {
+ errs = append(errs, errors.New("source entry identity key is required"))
+ }
+ case SourceKindAdvanceBackfill:
default:
errs = append(errs, fmt.Errorf("invalid release source kind: %s", i.SourceKind))
}📝 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 (i ReleasePlanInput) Validate() error { | |
| var errs []error | |
| if err := i.Plan.Record.ValidateForReference(); err != nil { | |
| errs = append(errs, fmt.Errorf("plan: %w", err)) | |
| } | |
| if i.Plan.Kind != ledger.BreakageKindPlan { | |
| errs = append(errs, errors.New("plan record must have kind plan")) | |
| } | |
| if err := ledger.ValidateTransactionAmount(i.Amount); err != nil { | |
| errs = append(errs, fmt.Errorf("amount: %w", err)) | |
| } | |
| if i.Amount.GreaterThan(i.Plan.OpenAmount) { | |
| errs = append(errs, errors.New("release amount cannot exceed open plan amount")) | |
| } | |
| if i.Plan.FBOAddress == nil { | |
| errs = append(errs, errors.New("plan FBO address is required")) | |
| } | |
| if i.Plan.BreakageAddress == nil { | |
| errs = append(errs, errors.New("plan breakage address is required")) | |
| } | |
| switch i.SourceKind { | |
| case SourceKindUsage, SourceKindUsageCorrection, SourceKindCreditPurchaseCorrection, SourceKindAdvanceBackfill: | |
| default: | |
| errs = append(errs, fmt.Errorf("invalid release source kind: %s", i.SourceKind)) | |
| } | |
| return errors.Join(errs...) | |
| func (i ReleasePlanInput) Validate() error { | |
| var errs []error | |
| if err := i.Plan.Record.ValidateForReference(); err != nil { | |
| errs = append(errs, fmt.Errorf("plan: %w", err)) | |
| } | |
| if i.Plan.Kind != ledger.BreakageKindPlan { | |
| errs = append(errs, errors.New("plan record must have kind plan")) | |
| } | |
| if err := ledger.ValidateTransactionAmount(i.Amount); err != nil { | |
| errs = append(errs, fmt.Errorf("amount: %w", err)) | |
| } | |
| if i.Amount.GreaterThan(i.Plan.OpenAmount) { | |
| errs = append(errs, errors.New("release amount cannot exceed open plan amount")) | |
| } | |
| if i.Plan.FBOAddress == nil { | |
| errs = append(errs, errors.New("plan FBO address is required")) | |
| } | |
| if i.Plan.BreakageAddress == nil { | |
| errs = append(errs, errors.New("plan breakage address is required")) | |
| } | |
| switch i.SourceKind { | |
| case SourceKindUsage, SourceKindUsageCorrection, SourceKindCreditPurchaseCorrection: | |
| if i.SourceEntryIdentityKey == "" { | |
| errs = append(errs, errors.New("source entry identity key is required")) | |
| } | |
| case SourceKindAdvanceBackfill: | |
| default: | |
| errs = append(errs, fmt.Errorf("invalid release source kind: %s", i.SourceKind)) | |
| } | |
| return 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/breakage/service.go` around lines 162 - 195,
ReleasePlanInput.Validate currently allows SourceKind values like
SourceKindUsage / SourceKindUsageCorrection / SourceKindCreditPurchaseCorrection
/ SourceKindAdvanceBackfill while leaving SourceEntryIdentityKey empty, which
breaks later source-linked lookups; update ReleasePlanInput.Validate (the
function named ReleasePlanInput.Validate) to require a non-empty
SourceEntryIdentityKey when i.SourceKind is one of those source-linked kinds
(append an error like "source entry identity is required for source-linked
releases" to errs if the field is empty), keeping the existing invalid-kind
default branch intact.
| BookedAt: input.AllocateAt, | ||
| SourceBalanceAsOf: clock.Now(), |
There was a problem hiding this comment.
Align source snapshot time with booked allocation time
On Line 248, SourceBalanceAsOf: clock.Now() can drift from Line 247 BookedAt: input.AllocateAt, which makes delayed/replayed runs non-deterministic and may allocate against a later balance than the booked event time.
Using the same as-of timestamp as booking keeps the collection boundary stable.
Suggested fix
- BookedAt: input.AllocateAt,
- SourceBalanceAsOf: clock.Now(),
+ BookedAt: input.AllocateAt,
+ SourceBalanceAsOf: input.AllocateAt,📝 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.
| BookedAt: input.AllocateAt, | |
| SourceBalanceAsOf: clock.Now(), | |
| BookedAt: input.AllocateAt, | |
| SourceBalanceAsOf: input.AllocateAt, |
🤖 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/chargeadapter/usagebased.go` around lines 247 - 248, The
SourceBalanceAsOf timestamp is using clock.Now() while BookedAt uses
input.AllocateAt, causing non-determinism on delayed/replayed runs; update the
construction that sets BookedAt: input.AllocateAt and SourceBalanceAsOf:
clock.Now() (in the allocation/charge creation code around the UsageBased charge
builder) to use the same as-of time by assigning SourceBalanceAsOf:
input.AllocateAt so the collection boundary matches the booking time.
| if c.deps.AccountCatalog == nil { | ||
| return nil, fmt.Errorf("account catalog is required") | ||
| } | ||
|
|
||
| if c.deps.BalanceQuerier == nil { | ||
| return nil, fmt.Errorf("balance querier is required") | ||
| } | ||
|
|
||
| customerAccounts, err := c.deps.AccountService.GetCustomerAccounts(ctx, customerID) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("get customer accounts: %w", err) | ||
| } |
There was a problem hiding this comment.
Add a nil guard for AccountService before use.
AccountCatalog and BalanceQuerier are validated, but AccountService is used at Line 114 without a guard. A nil config will crash here.
Suggested patch
if c.deps.BalanceQuerier == nil {
return nil, fmt.Errorf("balance querier is required")
}
+ if c.deps.AccountService == nil {
+ return nil, fmt.Errorf("account service is required")
+ }
customerAccounts, err := c.deps.AccountService.GetCustomerAccounts(ctx, customerID)🤖 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/collection_fbo.go` around lines 106 - 117, Add a
nil guard for c.deps.AccountService before it is used: check if
c.deps.AccountService == nil and return a descriptive error (e.g., "account
service is required") just like the existing checks for AccountCatalog and
BalanceQuerier, then call c.deps.AccountService.GetCustomerAccounts(ctx,
customerID); this prevents a nil dereference when invoking GetCustomerAccounts
on AccountService.
| -- create index "ledgerbreakagerecord_id" to table: "ledger_breakage_records" | ||
| CREATE UNIQUE INDEX "ledgerbreakagerecord_id" ON "ledger_breakage_records" ("id"); |
There was a problem hiding this comment.
Remove redundant unique index on id.
Since id is already the PRIMARY KEY (line 26), creating a separate unique index on it is redundant. PostgreSQL automatically creates a unique index for primary key columns, so this extra index wastes storage and adds unnecessary maintenance overhead.
🔧 Suggested fix
-- create index "ledgerbreakagerecord_annotations" to table: "ledger_breakage_records"
CREATE INDEX "ledgerbreakagerecord_annotations" ON "ledger_breakage_records" USING gin ("annotations");
--- create index "ledgerbreakagerecord_id" to table: "ledger_breakage_records"
-CREATE UNIQUE INDEX "ledgerbreakagerecord_id" ON "ledger_breakage_records" ("id");
-- create index "ledgerbreakagerecord_namespace" to table: "ledger_breakage_records"
CREATE INDEX "ledgerbreakagerecord_namespace" ON "ledger_breakage_records" ("namespace");📝 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.
| -- create index "ledgerbreakagerecord_id" to table: "ledger_breakage_records" | |
| CREATE UNIQUE INDEX "ledgerbreakagerecord_id" ON "ledger_breakage_records" ("id"); | |
| -- create index "ledgerbreakagerecord_annotations" to table: "ledger_breakage_records" | |
| CREATE INDEX "ledgerbreakagerecord_annotations" ON "ledger_breakage_records" USING gin ("annotations"); | |
| -- create index "ledgerbreakagerecord_namespace" to table: "ledger_breakage_records" | |
| CREATE INDEX "ledgerbreakagerecord_namespace" ON "ledger_breakage_records" ("namespace"); |
🤖 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
`@tools/migrate/migrations/20260511211059_add_credit_expiration_breakage.up.sql`
around lines 30 - 31, The migration creates a redundant unique index on the
primary key; remove the CREATE UNIQUE INDEX "ledgerbreakagerecord_id" ON
"ledger_breakage_records" ("id"); statement so the migration only relies on the
existing PRIMARY KEY on "id" and avoids creating the duplicate index.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
openmeter/ledger/chargeadapter/creditpurchase_test.go (1)
108-117: ⚡ Quick winUse numeric equality assertions instead of boolean decimal comparisons.
Please switch these
require.True(...Equal(...))assertions torequire.Equal(..., actual.InexactFloat64())per the test guideline foralpacadecimal.Decimal.Suggested patch
- require.True(t, rows[0].Amount.Equal(alpacadecimal.NewFromInt(100)), "plan amount: %s", rows[0].Amount) + require.Equal(t, 100.0, rows[0].Amount.InexactFloat64(), "plan amount: %s", rows[0].Amount) - require.True(t, env.sumBalanceAsOf(t, fbo, charge.CreatedAt).Equal(alpacadecimal.NewFromInt(100))) - require.True(t, env.sumBalanceAsOf(t, breakageSubAccount, charge.CreatedAt).Equal(alpacadecimal.Zero)) - require.True(t, env.sumBalanceAsOf(t, fbo, expiresAt).Equal(alpacadecimal.Zero)) - require.True(t, env.sumBalanceAsOf(t, breakageSubAccount, expiresAt).Equal(alpacadecimal.NewFromInt(100))) + require.Equal(t, 100.0, env.sumBalanceAsOf(t, fbo, charge.CreatedAt).InexactFloat64()) + require.Equal(t, 0.0, env.sumBalanceAsOf(t, breakageSubAccount, charge.CreatedAt).InexactFloat64()) + require.Equal(t, 0.0, env.sumBalanceAsOf(t, fbo, expiresAt).InexactFloat64()) + require.Equal(t, 100.0, env.sumBalanceAsOf(t, breakageSubAccount, expiresAt).InexactFloat64()) - require.True(t, byKind[ledger.BreakageKindPlan].Equal(alpacadecimal.NewFromInt(100))) - require.True(t, byKind[ledger.BreakageKindRelease].Equal(alpacadecimal.NewFromInt(40))) + require.Equal(t, 100.0, byKind[ledger.BreakageKindPlan].InexactFloat64()) + require.Equal(t, 40.0, byKind[ledger.BreakageKindRelease].InexactFloat64()) - require.True(t, env.sumBalanceAsOf(t, fbo, charge.CreatedAt).Equal(alpacadecimal.NewFromInt(60))) - require.True(t, env.sumBalanceAsOf(t, breakageSubAccount, charge.CreatedAt).Equal(alpacadecimal.Zero)) - require.True(t, env.sumBalanceAsOf(t, fbo, expiresAt).Equal(alpacadecimal.Zero)) - require.True(t, env.sumBalanceAsOf(t, breakageSubAccount, expiresAt).Equal(alpacadecimal.NewFromInt(60))) + require.Equal(t, 60.0, env.sumBalanceAsOf(t, fbo, charge.CreatedAt).InexactFloat64()) + require.Equal(t, 0.0, env.sumBalanceAsOf(t, breakageSubAccount, charge.CreatedAt).InexactFloat64()) + require.Equal(t, 0.0, env.sumBalanceAsOf(t, fbo, expiresAt).InexactFloat64()) + require.Equal(t, 60.0, env.sumBalanceAsOf(t, breakageSubAccount, expiresAt).InexactFloat64())As per coding guidelines "When asserting
alpacadecimal.Decimalequality in Go tests, preferrequire.Equal(t, expectedFloat64, actual.InexactFloat64())over boolean assertions likerequire.True(t, expected.Equal(actual))."Also applies to: 146-155
🤖 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/chargeadapter/creditpurchase_test.go` around lines 108 - 117, Replace boolean Decimal equality checks with numeric assertions: where the test uses require.True(...Equal(...)) for alpacadecimal.Decimal (e.g. rows[0].Amount.Equal(...), and results returned by env.sumBalanceAsOf(t, ...)), change them to require.Equal(t, expectedFloat64, actual.InexactFloat64()) using the expected value as a float64 (e.g. 100.0 or 0.0) and call InexactFloat64() on the actual Decimal (rows[0].Amount, env.sumBalanceAsOf(...) returns) to assert equality; apply the same change for the other decimal comparisons referenced (also around lines 146-155) while leaving non-decimal comparisons (like time.Equal on expiresAt) untouched.openmeter/ledger/collector/correct.go (1)
568-617: ⚡ Quick winAdd contract docstrings for the new correction-order helpers
These helpers encode pretty subtle business behavior (which FBO source entries are considered and in what unwind order), so a short contract docstring would make call sites much safer to read and maintain.
As per coding guidelines: "Add a docstring to domain helpers when the name compresses important business semantics that are easy to misread at call sites; explain the observable business contract and excluded cases, not implementation mechanics".
🤖 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/correct.go` around lines 568 - 617, The two new helpers correctedFBOEntriesForAmount and compareCollectedFBOCorrectionSourceEntries lack contract docstrings; add concise comments above each explaining the observable business contract: for correctedFBOEntriesForAmount(state the function considers only ledger.Entry items whose PostingAddress().AccountType() == ledger.AccountTypeCustomerFBO and whose Amount() is negative, that the amount parameter is the positive remaining amount to allocate, that the returned slice contains correctedFBOEntry items with amount fields summing up to at most the requested amount and that entries are chosen/unwound from the highest-priority source according to compareCollectedFBOCorrectionSourceEntries), and for compareCollectedFBOCorrectionSourceEntries(state the tie-breakers and priority order it enforces: use AnnotationCollectionSourceOrder when present, then customerFBOPriority(Route()), then SubAccountID(), then IdentityKey(); callers may rely on this comparator for deterministic unwind ordering and should treat entries not matching the CustomerFBO/negative-amount predicate as out-of-scope). Ensure both docstrings mention excluded cases and the stable/deterministic ordering contract.
🤖 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/correct.go`:
- Around line 299-307: The code appends advance-backfill reopen inputs returned
by resolveAdvanceBackfillBreakageReopenInputs directly into actions as
plannedDirectInputs, which can double-reopen the same backingGroup when multiple
corrections touch it; modify the planning logic so that advance-backfill reopen
resolution is done in a merged phase keyed by backingGroup (or maintain an
in-memory map of remaining-open amounts per backingGroup during planning) rather
than producing separate plannedDirectInputs for each call—specifically, stop
appending reopenInputs directly from resolveAdvanceBackfillBreakageReopenInputs
into actions, aggregate or deduct reopen amounts by backingGroup (using
backingGroup as the key) and only emit merged plannedDirectInputs after
resolving consumption across all correction items (the same change should be
applied to the other occurrence around lines 386-425 where
resolveAdvanceBackfillBreakageReopenInputs is used).
In `@openmeter/ledger/customerbalance/README.md`:
- Line 135: Replace the inconsistent casing/typo "Customerbalance" in the README
with the canonical package name "customerbalance" (or the phrase "customer
balance" if prose is preferred) so it matches the rest of the documentation;
search for occurrences of "Customerbalance" and update them to "customerbalance"
(or "customer balance") in the README and any adjacent docs to maintain
consistent naming.
---
Nitpick comments:
In `@openmeter/ledger/chargeadapter/creditpurchase_test.go`:
- Around line 108-117: Replace boolean Decimal equality checks with numeric
assertions: where the test uses require.True(...Equal(...)) for
alpacadecimal.Decimal (e.g. rows[0].Amount.Equal(...), and results returned by
env.sumBalanceAsOf(t, ...)), change them to require.Equal(t, expectedFloat64,
actual.InexactFloat64()) using the expected value as a float64 (e.g. 100.0 or
0.0) and call InexactFloat64() on the actual Decimal (rows[0].Amount,
env.sumBalanceAsOf(...) returns) to assert equality; apply the same change for
the other decimal comparisons referenced (also around lines 146-155) while
leaving non-decimal comparisons (like time.Equal on expiresAt) untouched.
In `@openmeter/ledger/collector/correct.go`:
- Around line 568-617: The two new helpers correctedFBOEntriesForAmount and
compareCollectedFBOCorrectionSourceEntries lack contract docstrings; add concise
comments above each explaining the observable business contract: for
correctedFBOEntriesForAmount(state the function considers only ledger.Entry
items whose PostingAddress().AccountType() == ledger.AccountTypeCustomerFBO and
whose Amount() is negative, that the amount parameter is the positive remaining
amount to allocate, that the returned slice contains correctedFBOEntry items
with amount fields summing up to at most the requested amount and that entries
are chosen/unwound from the highest-priority source according to
compareCollectedFBOCorrectionSourceEntries), and for
compareCollectedFBOCorrectionSourceEntries(state the tie-breakers and priority
order it enforces: use AnnotationCollectionSourceOrder when present, then
customerFBOPriority(Route()), then SubAccountID(), then IdentityKey(); callers
may rely on this comparator for deterministic unwind ordering and should treat
entries not matching the CustomerFBO/negative-amount predicate as out-of-scope).
Ensure both docstrings mention excluded cases and the stable/deterministic
ordering contract.
🪄 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: 71e3c5d6-f171-420d-814e-d0bd8253eca9
⛔ Files ignored due to path filters (31)
api/v3/openapi.yamlis excluded by!**/openapi.yamlgo.sumis excluded by!**/*.sum,!**/*.sumopenmeter/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/client.gois excluded by!**/ent/db/**openmeter/ent/db/cursor.gois excluded by!**/ent/db/**openmeter/ent/db/ent.gois excluded by!**/ent/db/**openmeter/ent/db/entmixinaccessor.gois excluded by!**/ent/db/**openmeter/ent/db/expose.gois excluded by!**/ent/db/**openmeter/ent/db/hook/hook.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord/ledgerbreakagerecord.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord/where.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_create.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_delete.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_query.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_update.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry/ledgerentry.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry/where.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry_create.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/paginate.gois excluded by!**/ent/db/**openmeter/ent/db/predicate/predicate.gois excluded by!**/ent/db/**openmeter/ent/db/runtime.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**openmeter/ent/db/tx.gois excluded by!**/ent/db/**
📒 Files selected for processing (72)
api/spec/packages/aip/src/customers/credits/grant.tspapi/spec/packages/aip/src/customers/credits/ledger.tspapi/spec/packages/aip/src/customers/credits/operations.tspapi/v3/api.gen.goapi/v3/filters/parse.goapi/v3/filters/parse_test.goapi/v3/handlers/customers/credits/convert.goapi/v3/handlers/customers/credits/get_balance.goapi/v3/handlers/customers/credits/list_transactions_test.goapp/common/billing.goapp/common/charges.goapp/common/customerbalance.gocmd/billing-worker/wire_gen.gocmd/jobs/internal/wire_gen.gocmd/server/wire_gen.goopenmeter/billing/charges/creditpurchase/adapter/charge.goopenmeter/billing/charges/creditpurchase/adapter/funded_credit_activity.goopenmeter/billing/charges/creditpurchase/adapter/funded_credit_activity_test.goopenmeter/billing/charges/creditpurchase/adapter/mapper.goopenmeter/billing/charges/creditpurchase/charge.goopenmeter/billing/charges/creditpurchase/funded_credit_activity.goopenmeter/billing/charges/creditpurchase/service/promotional.goopenmeter/billing/creditgrant/service.goopenmeter/billing/creditgrant/service/service.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.goopenmeter/ent/schema/chargescreditpurchase.goopenmeter/ent/schema/ledger_breakage_record.goopenmeter/ent/schema/ledger_entry.goopenmeter/ledger/account.goopenmeter/ledger/account/account.goopenmeter/ledger/annotations.goopenmeter/ledger/balance.goopenmeter/ledger/breakage/README.mdopenmeter/ledger/breakage/adapter/adapter.goopenmeter/ledger/breakage/adapter/record.goopenmeter/ledger/breakage/breakage_impacts.goopenmeter/ledger/breakage/noop.goopenmeter/ledger/breakage/service.goopenmeter/ledger/breakage/types.goopenmeter/ledger/chargeadapter/creditpurchase.goopenmeter/ledger/chargeadapter/creditpurchase_test.goopenmeter/ledger/chargeadapter/flatfee.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/helpers.goopenmeter/ledger/chargeadapter/usagebased.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/collector/README.mdopenmeter/ledger/collector/collect.goopenmeter/ledger/collector/collection_fbo.goopenmeter/ledger/collector/collection_fbo_test.goopenmeter/ledger/collector/correct.goopenmeter/ledger/collector/service.goopenmeter/ledger/customerbalance/README.mdopenmeter/ledger/customerbalance/expired_loader.goopenmeter/ledger/customerbalance/expired_loader_test.goopenmeter/ledger/customerbalance/facade.goopenmeter/ledger/customerbalance/facade_test.goopenmeter/ledger/customerbalance/funded_loader.goopenmeter/ledger/customerbalance/ledger_loader.goopenmeter/ledger/customerbalance/loaders.goopenmeter/ledger/customerbalance/noop.goopenmeter/ledger/customerbalance/service.goopenmeter/ledger/customerbalance/service_test.goopenmeter/ledger/customerbalance/testenv_test.goopenmeter/ledger/customerbalance/transactions.goopenmeter/ledger/customerbalance/transactions_test.goopenmeter/ledger/historical/adapter/ledger.goopenmeter/ledger/historical/adapter/ledger_test.goopenmeter/ledger/historical/adapter/sumentries_query.goopenmeter/ledger/historical/balance.goopenmeter/ledger/historical/entry.goopenmeter/ledger/impact.go
✅ Files skipped from review due to trivial changes (7)
- api/spec/packages/aip/src/customers/credits/operations.tsp
- openmeter/ent/schema/chargescreditpurchase.go
- cmd/billing-worker/wire_gen.go
- openmeter/billing/creditgrant/service.go
- cmd/jobs/internal/wire_gen.go
- openmeter/ledger/collector/README.md
- cmd/server/wire_gen.go
🚧 Files skipped from review as they are similar to previous changes (54)
- openmeter/billing/charges/creditpurchase/adapter/mapper.go
- openmeter/ledger/customerbalance/funded_loader.go
- openmeter/ledger/customerbalance/ledger_loader.go
- api/v3/handlers/customers/credits/list_transactions_test.go
- openmeter/ledger/account/account.go
- openmeter/ledger/chargeadapter/flatfee_test.go
- openmeter/ledger/chargeadapter/usagebased.go
- openmeter/ledger/historical/adapter/sumentries_query.go
- openmeter/ledger/chargeadapter/helpers.go
- openmeter/billing/charges/creditpurchase/charge.go
- openmeter/ledger/customerbalance/transactions_test.go
- openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity.go
- api/v3/handlers/customers/credits/get_balance.go
- api/spec/packages/aip/src/customers/credits/grant.tsp
- openmeter/ledger/customerbalance/noop.go
- app/common/billing.go
- openmeter/billing/creditgrant/service/service.go
- app/common/customerbalance.go
- openmeter/ledger/account.go
- openmeter/ledger/customerbalance/testenv_test.go
- openmeter/billing/charges/creditpurchase/funded_credit_activity.go
- api/v3/filters/parse.go
- openmeter/ledger/breakage/noop.go
- openmeter/billing/charges/creditpurchase/service/promotional.go
- app/common/charges.go
- openmeter/billing/charges/creditpurchase/adapter/charge.go
- api/v3/filters/parse_test.go
- openmeter/ledger/breakage/adapter/adapter.go
- openmeter/ledger/customerbalance/expired_loader.go
- api/v3/handlers/customers/credits/convert.go
- api/spec/packages/aip/src/customers/credits/ledger.tsp
- openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity_test.go
- openmeter/ledger/chargeadapter/usagebased_test.go
- openmeter/ledger/historical/balance.go
- openmeter/ledger/customerbalance/service_test.go
- openmeter/ledger/breakage/adapter/record.go
- openmeter/ledger/customerbalance/service.go
- openmeter/ledger/breakage/breakage_impacts.go
- openmeter/ent/schema/ledger_breakage_record.go
- openmeter/ledger/historical/adapter/ledger_test.go
- openmeter/ledger/customerbalance/facade_test.go
- openmeter/ledger/historical/entry.go
- openmeter/ledger/impact.go
- openmeter/ledger/customerbalance/facade.go
- openmeter/ledger/customerbalance/loaders.go
- openmeter/ledger/collector/service.go
- openmeter/ledger/customerbalance/expired_loader_test.go
- openmeter/ledger/customerbalance/transactions.go
- openmeter/ledger/collector/collection_fbo_test.go
- openmeter/ledger/balance.go
- openmeter/ledger/historical/adapter/ledger.go
- openmeter/ledger/chargeadapter/creditpurchase.go
- openmeter/ledger/breakage/service.go
- openmeter/ledger/breakage/types.go
| @T10 [reopen] 2 | ||
| ``` | ||
|
|
||
| Customerbalance should show one net expired row: |
There was a problem hiding this comment.
Use consistent package naming in the docs
Customerbalance looks like a typo/inconsistent casing. Prefer customerbalance (or “customer balance”) to match the rest of the doc/package naming.
As per coding guidelines: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness".
🤖 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/customerbalance/README.md` at line 135, Replace the
inconsistent casing/typo "Customerbalance" in the README with the canonical
package name "customerbalance" (or the phrase "customer balance" if prose is
preferred) so it matches the rest of the documentation; search for occurrences
of "Customerbalance" and update them to "customerbalance" (or "customer
balance") in the README and any adjacent docs to maintain consistent naming.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openmeter/ledger/breakage/breakage_impacts.go (1)
54-54: ⚡ Quick winUse
models.NewNillableGenericValidationErrorfor validation error wrapping.Per coding guidelines,
Validate() errormethods should return validation errors wrapped withmodels.NewNillableGenericValidationError(errors.Join(errs...)).♻️ Suggested fix
- return errors.Join(errs...) + return models.NewNillableGenericValidationError(errors.Join(errs...))As per coding guidelines: "For
Validate() errormethods, 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/breakage/breakage_impacts.go` at line 54, The Validate() implementation currently returns errors.Join(errs...), change it to wrap the joined errors with models.NewNillableGenericValidationError(errors.Join(errs...)) so the method returns a nillable generic validation error as required by guidelines; update the return in the Validate function (e.g., the Validate method for BreakageImpacts) to use models.NewNillableGenericValidationError(...) instead of returning errors.Join(errs...).
🤖 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.
Nitpick comments:
In `@openmeter/ledger/breakage/breakage_impacts.go`:
- Line 54: The Validate() implementation currently returns errors.Join(errs...),
change it to wrap the joined errors with
models.NewNillableGenericValidationError(errors.Join(errs...)) so the method
returns a nillable generic validation error as required by guidelines; update
the return in the Validate function (e.g., the Validate method for
BreakageImpacts) to use models.NewNillableGenericValidationError(...) instead of
returning errors.Join(errs...).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 6dbb9b9f-970f-41a6-8df3-3d44e16beaa6
📒 Files selected for processing (23)
api/v3/filters/parse.goapp/common/charges.goe2e/customer_credits_v3_test.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.goopenmeter/ent/schema/ledger_breakage_record.goopenmeter/ledger/breakage/adapter/record.goopenmeter/ledger/breakage/breakage_impacts.goopenmeter/ledger/breakage/service.goopenmeter/ledger/breakage/types.goopenmeter/ledger/chargeadapter/creditpurchase.goopenmeter/ledger/chargeadapter/creditpurchase_test.goopenmeter/ledger/chargeadapter/flatfee_test.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/service.goopenmeter/ledger/customerbalance/expired_loader_test.goopenmeter/ledger/customerbalance/testenv_test.gotest/app/stripe/invoice_test.gotest/credits/base.gotest/credits/creditgrant_test.go
✅ Files skipped from review due to trivial changes (1)
- openmeter/ledger/chargeadapter/usagebased_test.go
🚧 Files skipped from review as they are similar to previous changes (14)
- test/credits/creditgrant_test.go
- test/app/stripe/invoice_test.go
- openmeter/ledger/chargeadapter/flatfee_test.go
- openmeter/ledger/customerbalance/testenv_test.go
- openmeter/ledger/collector/correct.go
- openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
- openmeter/ledger/collector/collection_fbo.go
- app/common/charges.go
- openmeter/ledger/customerbalance/expired_loader_test.go
- openmeter/ledger/chargeadapter/creditpurchase_test.go
- openmeter/ledger/breakage/types.go
- openmeter/ledger/collector/collection_fbo_test.go
- openmeter/ledger/breakage/service.go
- test/credits/base.go
There was a problem hiding this comment.
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/creditpurchase/charge.go (1)
163-169:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAvoid early return in
Validate()so all errors are reported.Line [164] returns immediately, which skips the
ExpiresAtvalidation path and breaks aggregated validation behavior.Suggested fix
- if i.EffectiveAt != nil { - return errors.New("effective at is not yet supported") - } + if i.EffectiveAt != nil { + errs = append(errs, errors.New("effective at is not yet supported")) + }As per coding guidelines:
For Validate() error methods, collect all validation issues into var errs []error and return models.NewNillableGenericValidationError(errors.Join(errs...)) instead of returning on the first invalid field.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/billing/charges/creditpurchase/charge.go` around lines 163 - 169, The Validate method currently returns early when i.EffectiveAt != nil which prevents collecting other validation issues; change that early return into appending an error to errs (e.g., fmt.Errorf("effective at is not yet supported")) so the ExpiresAt check (and any other checks) still run, and at the end return models.NewNillableGenericValidationError(errors.Join(errs...)) (or nil when errs is empty); update the block containing the EffectiveAt check and ensure errs is declared/used consistently with the existing ExpiresAt validation.
♻️ Duplicate comments (1)
openmeter/ledger/customerbalance/README.md (1)
135-135:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUse consistent “customer balance” wording in prose.
Customerbalanceis inconsistent with the surrounding terminology. Please switch these tocustomer balance(orcustomerbalanceif you want to refer to the package name literally).Suggested doc tweak
-Customerbalance should show one net expired row: +Customer balance should show one net expired row:-For expired rows, customerbalance uses the cursor from the newest breakage transaction that contributed to the visible net impact. +For expired rows, customer balance uses the cursor from the newest breakage transaction that contributed to the visible net impact.As per coding guidelines: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness".
Also applies to: 163-163
🤖 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/customerbalance/README.md` at line 135, The README uses the term "Customerbalance" in prose which is inconsistent with surrounding terminology; update all prose occurrences of "Customerbalance" to "customer balance" (keep "customerbalance" only when referring to the package name literally) — search for the token "Customerbalance" and replace with "customer balance" in the README (including the instances around the current mentions) to maintain consistent wording.
🤖 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.
Outside diff comments:
In `@openmeter/billing/charges/creditpurchase/charge.go`:
- Around line 163-169: The Validate method currently returns early when
i.EffectiveAt != nil which prevents collecting other validation issues; change
that early return into appending an error to errs (e.g., fmt.Errorf("effective
at is not yet supported")) so the ExpiresAt check (and any other checks) still
run, and at the end return
models.NewNillableGenericValidationError(errors.Join(errs...)) (or nil when errs
is empty); update the block containing the EffectiveAt check and ensure errs is
declared/used consistently with the existing ExpiresAt validation.
---
Duplicate comments:
In `@openmeter/ledger/customerbalance/README.md`:
- Line 135: The README uses the term "Customerbalance" in prose which is
inconsistent with surrounding terminology; update all prose occurrences of
"Customerbalance" to "customer balance" (keep "customerbalance" only when
referring to the package name literally) — search for the token
"Customerbalance" and replace with "customer balance" in the README (including
the instances around the current mentions) to maintain consistent wording.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 05e5c2c6-ea84-4cc9-9631-30ade997ad9d
⛔ Files ignored due to path filters (32)
api/v3/openapi.yamlis excluded by!**/openapi.yamlgo.sumis excluded by!**/*.sum,!**/*.sumopenmeter/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/client.gois excluded by!**/ent/db/**openmeter/ent/db/cursor.gois excluded by!**/ent/db/**openmeter/ent/db/ent.gois excluded by!**/ent/db/**openmeter/ent/db/entmixinaccessor.gois excluded by!**/ent/db/**openmeter/ent/db/expose.gois excluded by!**/ent/db/**openmeter/ent/db/hook/hook.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord/ledgerbreakagerecord.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord/where.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_create.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_delete.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_query.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_update.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry/ledgerentry.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry/where.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry_create.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/paginate.gois excluded by!**/ent/db/**openmeter/ent/db/predicate/predicate.gois excluded by!**/ent/db/**openmeter/ent/db/runtime.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**openmeter/ent/db/tx.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (99)
api/spec/packages/aip/src/customers/credits/grant.tspapi/spec/packages/aip/src/customers/credits/ledger.tspapi/spec/packages/aip/src/customers/credits/operations.tspapi/v3/api.gen.goapi/v3/filters/parse.goapi/v3/filters/parse_test.goapi/v3/handlers/customers/credits/convert.goapi/v3/handlers/customers/credits/get_balance.goapi/v3/handlers/customers/credits/list_transactions_test.goapp/common/billing.goapp/common/charges.goapp/common/customerbalance.gocmd/billing-worker/wire_gen.gocmd/jobs/internal/wire_gen.gocmd/server/wire_gen.goe2e/customer_credits_v3_test.goopenmeter/billing/charges/creditpurchase/adapter/charge.goopenmeter/billing/charges/creditpurchase/adapter/funded_credit_activity.goopenmeter/billing/charges/creditpurchase/adapter/funded_credit_activity_test.goopenmeter/billing/charges/creditpurchase/adapter/mapper.goopenmeter/billing/charges/creditpurchase/charge.goopenmeter/billing/charges/creditpurchase/funded_credit_activity.goopenmeter/billing/charges/creditpurchase/service/promotional.goopenmeter/billing/creditgrant/service.goopenmeter/billing/creditgrant/service/service.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.goopenmeter/ent/schema/chargescreditpurchase.goopenmeter/ent/schema/ledger_breakage_record.goopenmeter/ent/schema/ledger_entry.goopenmeter/ledger/account.goopenmeter/ledger/account/account.goopenmeter/ledger/annotations.goopenmeter/ledger/balance.goopenmeter/ledger/breakage/README.mdopenmeter/ledger/breakage/adapter/adapter.goopenmeter/ledger/breakage/adapter/record.goopenmeter/ledger/breakage/breakage_impacts.goopenmeter/ledger/breakage/noop.goopenmeter/ledger/breakage/service.goopenmeter/ledger/breakage/types.goopenmeter/ledger/chargeadapter/creditpurchase.goopenmeter/ledger/chargeadapter/creditpurchase_test.goopenmeter/ledger/chargeadapter/flatfee.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/helpers.goopenmeter/ledger/chargeadapter/usagebased.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/collector/README.mdopenmeter/ledger/collector/collect.goopenmeter/ledger/collector/collection_fbo.goopenmeter/ledger/collector/collection_fbo_test.goopenmeter/ledger/collector/correct.goopenmeter/ledger/collector/service.goopenmeter/ledger/customerbalance/README.mdopenmeter/ledger/customerbalance/expired_loader.goopenmeter/ledger/customerbalance/expired_loader_test.goopenmeter/ledger/customerbalance/facade.goopenmeter/ledger/customerbalance/facade_test.goopenmeter/ledger/customerbalance/funded_loader.goopenmeter/ledger/customerbalance/ledger_loader.goopenmeter/ledger/customerbalance/loaders.goopenmeter/ledger/customerbalance/noop.goopenmeter/ledger/customerbalance/service.goopenmeter/ledger/customerbalance/service_test.goopenmeter/ledger/customerbalance/testenv_test.goopenmeter/ledger/customerbalance/transactions.goopenmeter/ledger/customerbalance/transactions_test.goopenmeter/ledger/historical/adapter/ledger.goopenmeter/ledger/historical/adapter/ledger_test.goopenmeter/ledger/historical/adapter/sumentries_query.goopenmeter/ledger/historical/balance.goopenmeter/ledger/historical/entry.goopenmeter/ledger/impact.goopenmeter/ledger/impact_test.goopenmeter/ledger/ledger_test.goopenmeter/ledger/noop/noop.goopenmeter/ledger/primitives.goopenmeter/ledger/query.goopenmeter/ledger/resolvers/account.goopenmeter/ledger/routingrules/defaults.goopenmeter/ledger/routingrules/routingrules.goopenmeter/ledger/routingrules/routingrules_test.goopenmeter/ledger/testutils/integration.goopenmeter/ledger/transactions/accrual.goopenmeter/ledger/transactions/breakage.goopenmeter/ledger/transactions/codes.goopenmeter/ledger/transactions/collection.goopenmeter/ledger/transactions/correction_leg.goopenmeter/ledger/transactions/entry_identity.goopenmeter/ledger/transactions/input.goopenmeter/ledger/transactions/testutils/anytransaction.gotest/app/stripe/invoice_test.gotest/credits/base.gotest/credits/creditgrant_test.gotest/credits/sanity_test.gotools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.down.sqltools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.up.sqltools/migrate/migrations/20260517121831_add_credit_expiration_breakage.down.sqltools/migrate/migrations/20260517121831_add_credit_expiration_breakage.up.sql
✅ Files skipped from review due to trivial changes (4)
- openmeter/billing/charges/creditpurchase/adapter/charge.go
- cmd/jobs/internal/wire_gen.go
- openmeter/ledger/collector/README.md
- cmd/server/wire_gen.go
🚧 Files skipped from review as they are similar to previous changes (79)
- openmeter/ent/schema/chargescreditpurchase.go
- openmeter/ent/schema/ledger_entry.go
- openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity.go
- tools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.up.sql
- openmeter/ledger/account/account.go
- openmeter/billing/charges/creditpurchase/service/promotional.go
- openmeter/ledger/chargeadapter/usagebased_test.go
- api/spec/packages/aip/src/customers/credits/operations.tsp
- test/credits/creditgrant_test.go
- app/common/customerbalance.go
- openmeter/ledger/chargeadapter/helpers.go
- openmeter/ledger/transactions/testutils/anytransaction.go
- openmeter/ledger/customerbalance/transactions_test.go
- openmeter/ledger/historical/entry.go
- openmeter/ledger/transactions/entry_identity.go
- openmeter/ledger/customerbalance/loaders.go
- openmeter/ledger/historical/adapter/sumentries_query.go
- openmeter/billing/creditgrant/service.go
- openmeter/ledger/chargeadapter/flatfee_test.go
- openmeter/ledger/customerbalance/expired_loader.go
- openmeter/ledger/resolvers/account.go
- openmeter/ledger/customerbalance/ledger_loader.go
- app/common/billing.go
- api/v3/handlers/customers/credits/list_transactions_test.go
- openmeter/ledger/customerbalance/noop.go
- openmeter/ledger/customerbalance/funded_loader.go
- api/v3/handlers/customers/credits/convert.go
- openmeter/ledger/customerbalance/service_test.go
- api/spec/packages/aip/src/customers/credits/ledger.tsp
- openmeter/ledger/collector/service.go
- api/v3/filters/parse_test.go
- openmeter/ledger/query.go
- openmeter/ledger/breakage/noop.go
- openmeter/ledger/routingrules/defaults.go
- openmeter/ledger/impact.go
- openmeter/ledger/breakage/adapter/adapter.go
- test/app/stripe/invoice_test.go
- e2e/customer_credits_v3_test.go
- openmeter/ledger/ledger_test.go
- openmeter/ledger/customerbalance/facade_test.go
- api/spec/packages/aip/src/customers/credits/grant.tsp
- openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity_test.go
- openmeter/billing/charges/creditpurchase/adapter/mapper.go
- openmeter/ledger/breakage/types.go
- openmeter/ledger/testutils/integration.go
- api/v3/filters/parse.go
- openmeter/ledger/chargeadapter/usagebased.go
- openmeter/billing/creditgrant/service/service.go
- openmeter/ledger/customerbalance/facade.go
- openmeter/ledger/chargeadapter/flatfee.go
- openmeter/ledger/chargeadapter/creditpurchase_test.go
- openmeter/ledger/primitives.go
- openmeter/ledger/annotations.go
- openmeter/ledger/account.go
- openmeter/ledger/transactions/breakage.go
- openmeter/ledger/historical/balance.go
- api/v3/handlers/customers/credits/get_balance.go
- openmeter/ledger/historical/adapter/ledger.go
- openmeter/ledger/chargeadapter/creditpurchase.go
- openmeter/ledger/customerbalance/testenv_test.go
- openmeter/ledger/collector/collection_fbo_test.go
- openmeter/ledger/routingrules/routingrules.go
- openmeter/ent/schema/ledger_breakage_record.go
- openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
- openmeter/ledger/customerbalance/transactions.go
- app/common/charges.go
- openmeter/ledger/breakage/breakage_impacts.go
- openmeter/ledger/historical/adapter/ledger_test.go
- openmeter/ledger/noop/noop.go
- openmeter/ledger/breakage/adapter/record.go
- openmeter/ledger/collector/correct.go
- openmeter/ledger/impact_test.go
- test/credits/base.go
- test/credits/sanity_test.go
- openmeter/ledger/customerbalance/expired_loader_test.go
- openmeter/ledger/collector/collection_fbo.go
- openmeter/ledger/customerbalance/service.go
- openmeter/ledger/transactions/accrual.go
- openmeter/ledger/breakage/service.go
…nt in transaction
|
superseded by this #4395 |
Summary
Adds ledger-backed credit expiration breakage tracking.
Expiring credits now pre-book future breakage entries at expiration time, release that planned breakage as credits are consumed, and reopen breakage when usage corrections restore previously consumed expiring credit. This keeps customer FBO balances correct across
asOfqueries while recording unused expired value on the breakage account.What Changed
asOf-aware ledger balance reads so future-dated expiration entries do not affect present-time balances unless explicitly queried.FBO -x / breakage +xFBO +x / breakage -xFBO -x / breakage +xNotes
Migrations
Adds:
charge_credit_purchases.expires_atledger_breakage_recordsledger_entries.identity_keyTests
asOfand breakage listing.Summary by CodeRabbit
New Features
Behavior
Documentation
Tests