Skip to content

feat!: breakage - #4371

Closed
GAlexIHU wants to merge 13 commits into
mainfrom
feat/breakage
Closed

GAlexIHU wants to merge 13 commits into
mainfrom
feat/breakage

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This would require a very complicated backfill. Breaking things and moving forward for an unstable non-public feature feels like an operationally more realistic path.

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 asOf queries while recording unused expired value on the breakage account.

What Changed

  • Added asOf-aware ledger balance reads so future-dated expiration entries do not affect present-time balances unless explicitly queried.
  • Added breakage ledger account support and breakage transaction templates:
    • plan: future FBO -x / breakage +x
    • release: future FBO +x / breakage -x
    • reopen: future FBO -x / breakage +x
  • Added persistent breakage records to link planned/released/reopened breakage transactions to ledger source entries.
  • Updated FBO collection to release breakage in the same deterministic source order used for credit consumption.
  • Updated correction flows so restored usage reopens the matching breakage release, including advance-backfill scenarios.
  • Added expiration support to credit purchase/grant creation paths.
  • Added customer balance transaction listing support for expired credit / breakage impact up to the queried time.
  • Added ledger entry identity keys so one transaction can safely contain multiple entries for the same sub-account when those entries represent distinct collection sources.
  • Added package README docs for the ledger collector, breakage, and customer balance logic.

Notes

  • Breakage rows are metadata/projection rows, not the accounting source of truth. Ledger entries remain the numeric source of truth.
  • Breakage uses deterministic collection order plus source-entry links for correction unwind.
  • Non-expiring credits do not create planned breakage.
  • Advance usage does not create breakage until real expiring credit backfills it; backfilled advance is immediately released because it was already used.

Migrations

Adds:

  • charge_credit_purchases.expires_at
  • ledger_breakage_records
  • ledger_entries.identity_key

Tests

  • Added ledger/customer balance coverage for asOf and breakage listing.
  • Added charge-adapter and sanity coverage for:
    • planned breakage on expiring credit issuance
    • release on usage
    • expiry reducing customer FBO balance
    • usage correction reopening breakage
    • multi-expiry correction unwind order
    • non-expiring sources during correction
    • advance backfill release
    • advance backfill correction reopening breakage

Summary by CodeRabbit

  • New Features

    • Expiring credits: grants can include expires_after/expires_at and an "expired" transaction type; credit issuance records planned expiry actions and ledger breakage.
    • As-of queries: balances and transaction listings accept an optional as_of timestamp.
  • Behavior

    • Balance and transaction views reflect as-of/expiry semantics; issuance and collection flows coordinate expiry-related ledger planning and releases.
  • Documentation

    • Added detailed breakage/expiry and as-of behavior docs.
  • Tests

    • Expanded unit, integration, and e2e tests covering expiry and as-of flows.

Review Change Stack

@GAlexIHU GAlexIHU added the release-note/feature Release note: Exciting New Features label May 17, 2026
@GAlexIHU
GAlexIHU requested a review from a team as a code owner May 17, 2026 11:29
@coderabbitai

coderabbitai Bot commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

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

Changes

Expiring Credits & Breakage

Layer / File(s) Summary
Breakage types, adapter, service, README
openmeter/ledger/breakage/*, openmeter/ent/schema/ledger_breakage_record.go
New durable breakage model, adapter, service (PlanIssuance/Release/Reopen), NoopService, persistence and listing logic, and comprehensive README.
Breakage impacts & listing
openmeter/ledger/breakage/breakage_impacts.go
Aggregates expired breakage records into customer-facing BreakageImpact with cursored pagination and validation.
Breakage adapter records
openmeter/ledger/breakage/adapter/*
Ent-backed adapter: transactional CreateRecords, ListCandidate/ListRelease/ListExpired with ForUpdate locking and mapping helpers.

Ledger identity, templates, and annotations

Layer / File(s) Summary
Entry identity & annotations
openmeter/ledger/primitives.go, openmeter/ledger/historical/entry.go, openmeter/ent/schema/ledger_entry.go
Adds Entry/EntryInput identityKey/annotations/ID, DB column + unique index, persistence and hydration updates.
Breakage transaction templates
openmeter/ledger/transactions/breakage.go, openmeter/ledger/transactions/codes.go
Adds Plan/Release/Reopen templates and template codes; templates resolve to two-entry transactions (FBO ↔ Breakage).
Transaction identity helpers & posting metadata
openmeter/ledger/transactions/*
Adds PostingAmount.identity/annotations, identity-key helpers, preserves identity/annotations on resolved EntryInputs, updates accrual templates and correction ordering.

Collector, corrector, and transactional plumbing

Layer / File(s) Summary
Collector & corrector changes
openmeter/ledger/collector/*
Collector/Corrector now run inside transaction.Run, accept TransactionManager and Breakage, select FBO sources as-of, resolve breakage release/reopen, accumulate pending records, commit ledger group and persist breakage records transactionally.
Service wiring & config
openmeter/ledger/collector/service.go, app/common/*, cmd/*/wire_gen.go
Thread Breakage, AccountLocker, TransactionManager through collector and billing registry; constructors return errors on missing deps and wire breakage service creation.
Charge adapters & issuance
openmeter/ledger/chargeadapter/*, openmeter/billing/charges/creditpurchase/*
Credit-purchase handler runs issuance in transaction, integrates PlanIssuance when ExpiresAt set, persists pending breakage records after commit, and updates intent ExpiresAt mapping/validation.

Balance, loaders, and customer-facing presentation

Layer / File(s) Summary
BalanceQuery & ledger balance APIs
openmeter/ledger/balance.go, openmeter/ledger/historical/*
Adds BalanceQuery {After, AsOf}; updates BalanceQuerier/GetAccountBalance/GetSubAccountBalance signatures and historical/Noop implementations to accept query.
Customer balance & loaders
openmeter/ledger/customerbalance/*
Adds AsOf filtering to GetBalances/GetBalance, facade validation, loaders for expired/funded/ledger transactions, expired transaction projection using Breakage.ListExpiredBreakageImpacts, and tests/docs.
Parsing & API spec
api/spec/*, api/v3/filters/parse.go, api/v3/handlers/customers/credits/*
API spec adds expires_after/expires_at and as_of filter; parse.go parses pointer fields implementing encoding.TextUnmarshaler (e.g., *time.Time) for filter[field]=value; handlers convert ExpiresAfter/ExpiresAt and map new expired transaction type.
Migrations
tools/migrate/*_add_ledger_entry_identity_key*.sql, *_add_credit_expiration_breakage*.sql
Adds identity_key column + unique index and new ledger_breakage_records table plus charge_credit_purchases.expires_at and supporting indexes; includes down migrations.

Tests & Docs

Layer / File(s) Summary
Unit & integration tests
openmeter/ledger/*_test.go, test/**, e2e/*, api/v3/filters/parse_test.go
Extensive tests covering parsing of filter[as_of], ExpiresAt/ExpiresAfter flows, breakage planning/release/reopen semantics, collector/corrector transactional behavior, historical adapter queries, loaders, and customer-facing listings.
READMEs
openmeter/ledger/collector/README.md, openmeter/ledger/breakage/README.md, openmeter/ledger/customerbalance/README.md
Documentation describing collection order, breakage semantics, expired impact computation, and transaction boundary requirements.
  • Estimated code review effort
    🎯 5 (Critical) | ⏱️ ~120 minutes

  • Possibly related PRs

  • Suggested labels
    area/billing

  • Suggested reviewers

    • turip
    • tothandras
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/breakage

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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 win

Apply the same AsOf cutoff 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-item Balance.Before/After values.

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 win

Scope the credit-movement subquery by namespace.

Right now the HAVING SUM(amount) selector scans and groups customer_fbo entries across every tenant, then the outer query filters back down to input.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 value

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

Prefer InexactFloat64() for decimal assertions.

Per coding guidelines, when comparing alpacadecimal.Decimal values in tests, use require.Equal(t, expectedFloat64, actual.InexactFloat64()) instead of require.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 win

Consider 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 TransactionTemplateCodeFromAnnotations should 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 win

Use the standard decimal assertion style in tests.

Tiny tweak: prefer comparing InexactFloat64() instead of boolean Equal(...) 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.Decimal equality in Go tests, prefer require.Equal(t, expectedFloat64, actual.InexactFloat64()) over boolean assertions like require.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 win

Prefer direct numeric equality assertions for decimals in tests.

These assertions currently use boolean Decimal.Equal(...), which gives weaker diffs on failure. Please use require.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.Decimal equality in Go tests, prefer require.Equal(t, expectedFloat64, actual.InexactFloat64()) over boolean assertions like require.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 win

Use clock.SetTime for 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 with defer 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 win

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

Please 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 with defer 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 win

Use the repo’s preferred decimal assertion style here.

These require.True(expected.Equal(actual)) checks should use require.Equal(..., actual.InexactFloat64()) for consistency across tests.

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

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 win

Please switch these decimal equality checks to the preferred assertion form.

Use require.Equal(t, expectedFloat64, actual.InexactFloat64()) instead of boolean require.True(decimal.Equal(...)) for consistency and clearer failures.

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

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 win

Use the repo-preferred decimal assertion style in these tests.

These assertions currently use require.True(...Equal(...)); please switch to require.Equal(t, expectedFloat64, actual.InexactFloat64()) for consistency and better failure output.

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

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 value

Minor 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. If ListReleases already 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

📥 Commits

Reviewing files that changed from the base of the PR and between daa002d and 6a1abb9.

⛔ Files ignored due to path filters (32)
  • api/v3/openapi.yaml is excluded by !**/openapi.yaml
  • go.sum is excluded by !**/*.sum, !**/*.sum
  • openmeter/ent/db/chargecreditpurchase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase/chargecreditpurchase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/cursor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ent.go is excluded by !**/ent/db/**
  • openmeter/ent/db/entmixinaccessor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/expose.go is excluded by !**/ent/db/**
  • openmeter/ent/db/hook/hook.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord/ledgerbreakagerecord.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerentry.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerentry/ledgerentry.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerentry/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerentry_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/paginate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/predicate/predicate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • openmeter/ent/db/tx.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (115)
  • .agents/skills/ledger/SKILL.md
  • api/spec/packages/aip/src/customers/credits/grant.tsp
  • api/spec/packages/aip/src/customers/credits/ledger.tsp
  • api/spec/packages/aip/src/customers/credits/operations.tsp
  • api/v3/api.gen.go
  • api/v3/filters/parse.go
  • api/v3/filters/parse_test.go
  • api/v3/handlers/customers/credits/convert.go
  • api/v3/handlers/customers/credits/get_balance.go
  • api/v3/handlers/customers/credits/list_transactions_test.go
  • app/common/billing.go
  • app/common/charges.go
  • app/common/customerbalance.go
  • cmd/billing-worker/wire_gen.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity.go
  • openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity_test.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper.go
  • openmeter/billing/charges/creditpurchase/charge.go
  • openmeter/billing/charges/creditpurchase/funded_credit_activity.go
  • openmeter/billing/charges/creditpurchase/service/promotional.go
  • openmeter/billing/creditgrant/service.go
  • openmeter/billing/creditgrant/service/service.go
  • openmeter/ent/schema/chargescreditpurchase.go
  • openmeter/ent/schema/ledger_breakage_record.go
  • openmeter/ent/schema/ledger_entry.go
  • openmeter/ledger/account.go
  • openmeter/ledger/account/account.go
  • openmeter/ledger/annotations.go
  • openmeter/ledger/annotations_test.go
  • openmeter/ledger/balance.go
  • openmeter/ledger/breakage/README.md
  • openmeter/ledger/breakage/adapter/adapter.go
  • openmeter/ledger/breakage/adapter/record.go
  • openmeter/ledger/breakage/breakage_impacts.go
  • openmeter/ledger/breakage/noop.go
  • openmeter/ledger/breakage/service.go
  • openmeter/ledger/breakage/types.go
  • openmeter/ledger/chargeadapter/creditpurchase.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
  • openmeter/ledger/chargeadapter/flatfee.go
  • openmeter/ledger/chargeadapter/flatfee_test.go
  • openmeter/ledger/chargeadapter/helpers.go
  • openmeter/ledger/chargeadapter/usagebased.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
  • openmeter/ledger/collector/README.md
  • openmeter/ledger/collector/collect.go
  • openmeter/ledger/collector/collection_fbo.go
  • openmeter/ledger/collector/collection_fbo_test.go
  • openmeter/ledger/collector/correct.go
  • openmeter/ledger/collector/service.go
  • openmeter/ledger/customerbalance/README.md
  • openmeter/ledger/customerbalance/expired_loader.go
  • openmeter/ledger/customerbalance/expired_loader_test.go
  • openmeter/ledger/customerbalance/facade.go
  • openmeter/ledger/customerbalance/facade_test.go
  • openmeter/ledger/customerbalance/funded_loader.go
  • openmeter/ledger/customerbalance/ledger_loader.go
  • openmeter/ledger/customerbalance/loaders.go
  • openmeter/ledger/customerbalance/noop.go
  • openmeter/ledger/customerbalance/service.go
  • openmeter/ledger/customerbalance/service_test.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • openmeter/ledger/customerbalance/transactions.go
  • openmeter/ledger/customerbalance/transactions_test.go
  • openmeter/ledger/historical/adapter/ledger.go
  • openmeter/ledger/historical/adapter/ledger_test.go
  • openmeter/ledger/historical/adapter/sumentries_query.go
  • openmeter/ledger/historical/balance.go
  • openmeter/ledger/historical/entry.go
  • openmeter/ledger/impact.go
  • openmeter/ledger/impact_test.go
  • openmeter/ledger/ledger_test.go
  • openmeter/ledger/noop/noop.go
  • openmeter/ledger/primitives.go
  • openmeter/ledger/query.go
  • openmeter/ledger/resolvers/account.go
  • openmeter/ledger/routingrules/defaults.go
  • openmeter/ledger/routingrules/routingrules.go
  • openmeter/ledger/routingrules/routingrules_test.go
  • openmeter/ledger/testutils/integration.go
  • openmeter/ledger/transactions/accrual.go
  • openmeter/ledger/transactions/accrual_test.go
  • openmeter/ledger/transactions/breakage.go
  • openmeter/ledger/transactions/codes.go
  • openmeter/ledger/transactions/collection.go
  • openmeter/ledger/transactions/correction.go
  • openmeter/ledger/transactions/correction_leg.go
  • openmeter/ledger/transactions/correction_test.go
  • openmeter/ledger/transactions/customer.go
  • openmeter/ledger/transactions/earnings.go
  • openmeter/ledger/transactions/earnings_test.go
  • openmeter/ledger/transactions/entry_identity.go
  • openmeter/ledger/transactions/fx.go
  • openmeter/ledger/transactions/input.go
  • openmeter/ledger/transactions/legacy.go
  • openmeter/ledger/transactions/resolve.go
  • openmeter/ledger/transactions/resolve_test.go
  • openmeter/ledger/transactions/template.go
  • openmeter/ledger/transactions/testutils/anytransaction.go
  • pkg/cmpx/compare.go
  • test/app/stripe/invoice_test.go
  • test/credits/base.go
  • test/credits/creditgrant_test.go
  • test/credits/sanity_test.go
  • tools/migrate/migrations/20260511134625_ledger_transaction_template_codes.down.sql
  • tools/migrate/migrations/20260511134625_ledger_transaction_template_codes.up.sql
  • tools/migrate/migrations/20260511211059_add_credit_expiration_breakage.down.sql
  • tools/migrate/migrations/20260511211059_add_credit_expiration_breakage.up.sql
  • tools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.down.sql
  • tools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.up.sql
  • tools/migrate/migrations/20260514154312_add_breakage_source_entry_id.down.sql
  • tools/migrate/migrations/20260514154312_add_breakage_source_entry_id.up.sql

}

func (s *ListFundedCreditActivitiesSuite) TestFiltersByAsOf() {
ctx := context.Background()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 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 -50

Repository: 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.

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

Comment on lines +33 to +35
field.String("identity_key").
Default("").
Immutable(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

🧩 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
fi

Repository: openmeterio/openmeter

Length of output: 676


🏁 Script executed:

cat openmeter/ent/schema/ledger_entry.go

Repository: openmeterio/openmeter

Length of output: 1784


🏁 Script executed:

fd -e sql . tools/migrate/migrations/ | rg identity_key

Repository: openmeterio/openmeter

Length of output: 221


🏁 Script executed:

cat tools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.down.sql

Repository: openmeterio/openmeter

Length of output: 342


🏁 Script executed:

fd -type f -name "*.up.sql" tools/migrate/migrations/ | xargs grep -l "ledger_entries" | head -10

Repository: 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 -20

Repository: 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 -5

Repository: openmeterio/openmeter

Length of output: 88


🏁 Script executed:

grep -A 30 "CREATE TABLE.*ledger_entries" tools/migrate/migrations/20260316165258_ledger.up.sql | head -40

Repository: 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.

Comment on lines +162 to +195
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...)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
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.

Comment thread openmeter/ledger/breakage/service.go Resolved
Comment on lines +247 to +248
BookedAt: input.AllocateAt,
SourceBalanceAsOf: clock.Now(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
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.

Comment on lines +106 to +117
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)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment thread openmeter/ledger/collector/service.go Resolved
Comment thread openmeter/ledger/transactions/codes.go Resolved
Comment on lines +30 to +31
-- create index "ledgerbreakagerecord_id" to table: "ledger_breakage_records"
CREATE UNIQUE INDEX "ledgerbreakagerecord_id" ON "ledger_breakage_records" ("id");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
-- 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
openmeter/ledger/chargeadapter/creditpurchase_test.go (1)

108-117: ⚡ Quick win

Use numeric equality assertions instead of boolean decimal comparisons.

Please switch these require.True(...Equal(...)) assertions to require.Equal(..., actual.InexactFloat64()) per the test guideline for alpacadecimal.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.Decimal equality in Go tests, prefer require.Equal(t, expectedFloat64, actual.InexactFloat64()) over boolean assertions like require.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 win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6a1abb9 and d617bf5.

⛔ Files ignored due to path filters (31)
  • api/v3/openapi.yaml is excluded by !**/openapi.yaml
  • go.sum is excluded by !**/*.sum, !**/*.sum
  • openmeter/ent/db/chargecreditpurchase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase/chargecreditpurchase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/cursor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ent.go is excluded by !**/ent/db/**
  • openmeter/ent/db/entmixinaccessor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/expose.go is excluded by !**/ent/db/**
  • openmeter/ent/db/hook/hook.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord/ledgerbreakagerecord.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerentry.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerentry/ledgerentry.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerentry/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerentry_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/paginate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/predicate/predicate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • openmeter/ent/db/tx.go is excluded by !**/ent/db/**
📒 Files selected for processing (72)
  • api/spec/packages/aip/src/customers/credits/grant.tsp
  • api/spec/packages/aip/src/customers/credits/ledger.tsp
  • api/spec/packages/aip/src/customers/credits/operations.tsp
  • api/v3/api.gen.go
  • api/v3/filters/parse.go
  • api/v3/filters/parse_test.go
  • api/v3/handlers/customers/credits/convert.go
  • api/v3/handlers/customers/credits/get_balance.go
  • api/v3/handlers/customers/credits/list_transactions_test.go
  • app/common/billing.go
  • app/common/charges.go
  • app/common/customerbalance.go
  • cmd/billing-worker/wire_gen.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity.go
  • openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity_test.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper.go
  • openmeter/billing/charges/creditpurchase/charge.go
  • openmeter/billing/charges/creditpurchase/funded_credit_activity.go
  • openmeter/billing/charges/creditpurchase/service/promotional.go
  • openmeter/billing/creditgrant/service.go
  • openmeter/billing/creditgrant/service/service.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • openmeter/ent/schema/chargescreditpurchase.go
  • openmeter/ent/schema/ledger_breakage_record.go
  • openmeter/ent/schema/ledger_entry.go
  • openmeter/ledger/account.go
  • openmeter/ledger/account/account.go
  • openmeter/ledger/annotations.go
  • openmeter/ledger/balance.go
  • openmeter/ledger/breakage/README.md
  • openmeter/ledger/breakage/adapter/adapter.go
  • openmeter/ledger/breakage/adapter/record.go
  • openmeter/ledger/breakage/breakage_impacts.go
  • openmeter/ledger/breakage/noop.go
  • openmeter/ledger/breakage/service.go
  • openmeter/ledger/breakage/types.go
  • openmeter/ledger/chargeadapter/creditpurchase.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
  • openmeter/ledger/chargeadapter/flatfee.go
  • openmeter/ledger/chargeadapter/flatfee_test.go
  • openmeter/ledger/chargeadapter/helpers.go
  • openmeter/ledger/chargeadapter/usagebased.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
  • openmeter/ledger/collector/README.md
  • openmeter/ledger/collector/collect.go
  • openmeter/ledger/collector/collection_fbo.go
  • openmeter/ledger/collector/collection_fbo_test.go
  • openmeter/ledger/collector/correct.go
  • openmeter/ledger/collector/service.go
  • openmeter/ledger/customerbalance/README.md
  • openmeter/ledger/customerbalance/expired_loader.go
  • openmeter/ledger/customerbalance/expired_loader_test.go
  • openmeter/ledger/customerbalance/facade.go
  • openmeter/ledger/customerbalance/facade_test.go
  • openmeter/ledger/customerbalance/funded_loader.go
  • openmeter/ledger/customerbalance/ledger_loader.go
  • openmeter/ledger/customerbalance/loaders.go
  • openmeter/ledger/customerbalance/noop.go
  • openmeter/ledger/customerbalance/service.go
  • openmeter/ledger/customerbalance/service_test.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • openmeter/ledger/customerbalance/transactions.go
  • openmeter/ledger/customerbalance/transactions_test.go
  • openmeter/ledger/historical/adapter/ledger.go
  • openmeter/ledger/historical/adapter/ledger_test.go
  • openmeter/ledger/historical/adapter/sumentries_query.go
  • openmeter/ledger/historical/balance.go
  • openmeter/ledger/historical/entry.go
  • openmeter/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

Comment thread openmeter/ledger/collector/correct.go Resolved
@T10 [reopen] 2
```

Customerbalance should show one net expired row:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

@GAlexIHU GAlexIHU changed the title feat: breakage feat!: breakage May 17, 2026
Comment thread api/v3/filters/parse.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
openmeter/ledger/breakage/breakage_impacts.go (1)

54-54: ⚡ Quick win

Use models.NewNillableGenericValidationError for validation error wrapping.

Per coding guidelines, Validate() error methods should return validation errors wrapped with models.NewNillableGenericValidationError(errors.Join(errs...)).

♻️ Suggested fix
-	return errors.Join(errs...)
+	return models.NewNillableGenericValidationError(errors.Join(errs...))

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/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

📥 Commits

Reviewing files that changed from the base of the PR and between a6c4e91 and 755f4af.

📒 Files selected for processing (23)
  • api/v3/filters/parse.go
  • app/common/charges.go
  • e2e/customer_credits_v3_test.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • openmeter/ent/schema/ledger_breakage_record.go
  • openmeter/ledger/breakage/adapter/record.go
  • openmeter/ledger/breakage/breakage_impacts.go
  • openmeter/ledger/breakage/service.go
  • openmeter/ledger/breakage/types.go
  • openmeter/ledger/chargeadapter/creditpurchase.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
  • openmeter/ledger/chargeadapter/flatfee_test.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
  • openmeter/ledger/collector/collect.go
  • openmeter/ledger/collector/collection_fbo.go
  • openmeter/ledger/collector/collection_fbo_test.go
  • openmeter/ledger/collector/correct.go
  • openmeter/ledger/collector/service.go
  • openmeter/ledger/customerbalance/expired_loader_test.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • test/app/stripe/invoice_test.go
  • test/credits/base.go
  • test/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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 win

Avoid early return in Validate() so all errors are reported.

Line [164] returns immediately, which skips the ExpiresAt validation 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 win

Use consistent “customer balance” wording in prose.

Customerbalance is inconsistent with the surrounding terminology. Please switch these to customer balance (or customerbalance if 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

📥 Commits

Reviewing files that changed from the base of the PR and between 755f4af and 6a56892.

⛔ Files ignored due to path filters (32)
  • api/v3/openapi.yaml is excluded by !**/openapi.yaml
  • go.sum is excluded by !**/*.sum, !**/*.sum
  • openmeter/ent/db/chargecreditpurchase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase/chargecreditpurchase.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchase_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/cursor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ent.go is excluded by !**/ent/db/**
  • openmeter/ent/db/entmixinaccessor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/expose.go is excluded by !**/ent/db/**
  • openmeter/ent/db/hook/hook.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord/ledgerbreakagerecord.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerbreakagerecord_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerentry.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerentry/ledgerentry.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerentry/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ledgerentry_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/paginate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/predicate/predicate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • openmeter/ent/db/tx.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (99)
  • api/spec/packages/aip/src/customers/credits/grant.tsp
  • api/spec/packages/aip/src/customers/credits/ledger.tsp
  • api/spec/packages/aip/src/customers/credits/operations.tsp
  • api/v3/api.gen.go
  • api/v3/filters/parse.go
  • api/v3/filters/parse_test.go
  • api/v3/handlers/customers/credits/convert.go
  • api/v3/handlers/customers/credits/get_balance.go
  • api/v3/handlers/customers/credits/list_transactions_test.go
  • app/common/billing.go
  • app/common/charges.go
  • app/common/customerbalance.go
  • cmd/billing-worker/wire_gen.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
  • e2e/customer_credits_v3_test.go
  • openmeter/billing/charges/creditpurchase/adapter/charge.go
  • openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity.go
  • openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity_test.go
  • openmeter/billing/charges/creditpurchase/adapter/mapper.go
  • openmeter/billing/charges/creditpurchase/charge.go
  • openmeter/billing/charges/creditpurchase/funded_credit_activity.go
  • openmeter/billing/charges/creditpurchase/service/promotional.go
  • openmeter/billing/creditgrant/service.go
  • openmeter/billing/creditgrant/service/service.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • openmeter/ent/schema/chargescreditpurchase.go
  • openmeter/ent/schema/ledger_breakage_record.go
  • openmeter/ent/schema/ledger_entry.go
  • openmeter/ledger/account.go
  • openmeter/ledger/account/account.go
  • openmeter/ledger/annotations.go
  • openmeter/ledger/balance.go
  • openmeter/ledger/breakage/README.md
  • openmeter/ledger/breakage/adapter/adapter.go
  • openmeter/ledger/breakage/adapter/record.go
  • openmeter/ledger/breakage/breakage_impacts.go
  • openmeter/ledger/breakage/noop.go
  • openmeter/ledger/breakage/service.go
  • openmeter/ledger/breakage/types.go
  • openmeter/ledger/chargeadapter/creditpurchase.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
  • openmeter/ledger/chargeadapter/flatfee.go
  • openmeter/ledger/chargeadapter/flatfee_test.go
  • openmeter/ledger/chargeadapter/helpers.go
  • openmeter/ledger/chargeadapter/usagebased.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
  • openmeter/ledger/collector/README.md
  • openmeter/ledger/collector/collect.go
  • openmeter/ledger/collector/collection_fbo.go
  • openmeter/ledger/collector/collection_fbo_test.go
  • openmeter/ledger/collector/correct.go
  • openmeter/ledger/collector/service.go
  • openmeter/ledger/customerbalance/README.md
  • openmeter/ledger/customerbalance/expired_loader.go
  • openmeter/ledger/customerbalance/expired_loader_test.go
  • openmeter/ledger/customerbalance/facade.go
  • openmeter/ledger/customerbalance/facade_test.go
  • openmeter/ledger/customerbalance/funded_loader.go
  • openmeter/ledger/customerbalance/ledger_loader.go
  • openmeter/ledger/customerbalance/loaders.go
  • openmeter/ledger/customerbalance/noop.go
  • openmeter/ledger/customerbalance/service.go
  • openmeter/ledger/customerbalance/service_test.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • openmeter/ledger/customerbalance/transactions.go
  • openmeter/ledger/customerbalance/transactions_test.go
  • openmeter/ledger/historical/adapter/ledger.go
  • openmeter/ledger/historical/adapter/ledger_test.go
  • openmeter/ledger/historical/adapter/sumentries_query.go
  • openmeter/ledger/historical/balance.go
  • openmeter/ledger/historical/entry.go
  • openmeter/ledger/impact.go
  • openmeter/ledger/impact_test.go
  • openmeter/ledger/ledger_test.go
  • openmeter/ledger/noop/noop.go
  • openmeter/ledger/primitives.go
  • openmeter/ledger/query.go
  • openmeter/ledger/resolvers/account.go
  • openmeter/ledger/routingrules/defaults.go
  • openmeter/ledger/routingrules/routingrules.go
  • openmeter/ledger/routingrules/routingrules_test.go
  • openmeter/ledger/testutils/integration.go
  • openmeter/ledger/transactions/accrual.go
  • openmeter/ledger/transactions/breakage.go
  • openmeter/ledger/transactions/codes.go
  • openmeter/ledger/transactions/collection.go
  • openmeter/ledger/transactions/correction_leg.go
  • openmeter/ledger/transactions/entry_identity.go
  • openmeter/ledger/transactions/input.go
  • openmeter/ledger/transactions/testutils/anytransaction.go
  • test/app/stripe/invoice_test.go
  • test/credits/base.go
  • test/credits/creditgrant_test.go
  • test/credits/sanity_test.go
  • tools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.down.sql
  • tools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.up.sql
  • tools/migrate/migrations/20260517121831_add_credit_expiration_breakage.down.sql
  • tools/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

turip
turip previously approved these changes May 18, 2026
@GAlexIHU GAlexIHU mentioned this pull request May 20, 2026
@GAlexIHU

Copy link
Copy Markdown
Contributor Author

superseded by this #4395

@GAlexIHU GAlexIHU closed this May 20, 2026

This branch was previously deployed

1 inactive deployment
dev — 39ec46d6 Deployed May 19, 2026 by GAlexIHU via Migration Checks #14475
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants