Skip to content

feat!: breakage - #4395

Merged
GAlexIHU merged 17 commits into
mainfrom
feat/breakage-rebased
May 20, 2026
Merged

GAlexIHU merged 17 commits into
mainfrom
feat/breakage-rebased

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

#4371

Overview

Fixes #(issue)

Notes for reviewer

Summary by CodeRabbit

  • New Features

    • Credits can have optional expiry (duration and calculated expiry timestamp).
    • Query customer credit balances and transactions "as-of" a specific timestamp.
    • New "expired" transaction type appears in credit histories.
    • Ledger breakage subsystem tracks planned/released/reopen expiry records and impacts.
  • Improvements

    • Currency filtering and balance/transaction queries respect as-of semantics.
    • Collection and ledger flows preserve identity keys, annotations, and transactional integrity.
  • Tests & Docs

    • Extensive tests and documentation for expiry, breakage, and as-of behaviors.

Review Change Stack

@GAlexIHU
GAlexIHU requested a review from a team as a code owner May 20, 2026 09:31
@GAlexIHU GAlexIHU added the release-note/ignore Ignore this change when generating release notes label May 20, 2026
@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Implements credit expiration (breakage) and point-in-time (as-of) balance/transaction support across API, ledger, collector, storage, wiring, migrations, docs, and tests.

Changes

Credit Expiration + As-Of Querying

Layer / File(s) Summary
API contracts and parsing
api/spec/packages/aip/*, api/v3/filters/*, api/v3/handlers/customers/credits/*, e2e/*
Adds expires_after/expires_at to grant model, expired transaction type, timestamp/AsOf query param, TextUnmarshaler/time pointer parsing, and handler conversions plus tests.
DB schema & adapter
openmeter/ent/schema/*, tools/migrate/*, openmeter/ledger/breakage/adapter/*
New ledger_breakage_records ent schema, identity_key on ledger entries, migrations, and Ent adapter create/list methods.
Breakage types & service
openmeter/ledger/breakage/*
Domain types, Adapter interface, service impl for plan/release/reopen, expired-impact aggregation, persistence/correlation, and noop service.
Collector & transactions
openmeter/ledger/collector/*, openmeter/ledger/transactions/*
Collector selection/order by expiry, integration with breakage planning/persistence, new breakage transaction templates, identity keys and annotations, and correction reopening/coalescing logic.
Customer balance & loaders
openmeter/ledger/customerbalance/*, openmeter/ledger/historical/*
BalanceQuery/AsOf added, expired transaction loader, loaders pass AsOf and exclude breakage annotations, historical ledger AsOf/exclude filters and scoped credit movement predicate.
Charges and credit purchase
openmeter/billing/charges/creditpurchase/*, app/common/*
Intent ExpiresAt persisted and validated, credit purchase handler runs in transaction, plans breakage, persists pending records; wiring and lineage backfill added.
Wiring, tests, docs, migrations
cmd/*/wire_gen.go, test/**/*, openmeter/ledger/*/README.md, tools/migrate/*
Wires breakage into app registries and cmd initializers, updates tests and adds new unit/integration/e2e tests and READMEs, and adds DB migrations for new columns/tables.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Suggested reviewers

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

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
openmeter/ledger/historical/adapter/ledger.go (1)

341-347: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Scope the credit-movement subquery to the request namespace.

Right now the IN (...) subquery aggregates FBO movement across every namespace, and the outer ledgertransactiondb.Namespace(...) filter only applies afterward. On a busy multi-tenant ledger, that makes a tenant-scoped list call do a much wider aggregate scan than needed.

Suggested fix
-			pred, err := ledgerTransactionCreditMovementPredicate(input.AccountIDs, input.Currency, input.CreditMovement)
+			pred, err := ledgerTransactionCreditMovementPredicate(input.Namespace, input.AccountIDs, input.Currency, input.CreditMovement)
 func ledgerTransactionCreditMovementPredicate(
+	namespace string,
 	accountIDs []string,
 	currency *currencyx.Code,
 	movement ledger.ListTransactionsCreditMovement,
 ) (predicate.LedgerTransaction, error) {
 	var having *sql.Predicate
@@
 	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 {
 	entries := sql.Table(ledgerentrydb.Table)
 	subAccounts := sql.Table(ledgersubaccountdb.Table)
 	accounts := sql.Table(ledgeraccountdb.Table)
 
 	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)).
 		Join(accounts).
 		On(subAccounts.C(ledgersubaccountdb.FieldAccountID), accounts.C(ledgeraccountdb.FieldID)).
 		Where(sql.EQ(accounts.C(ledgeraccountdb.FieldAccountType), ledger.AccountTypeCustomerFBO))

As per coding guidelines, performance should be a priority in database operations.

Also applies to: 476-534

🤖 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 341 - 347, The
credit-movement subquery built by ledgerTransactionCreditMovementPredicate is
currently unscoped and can aggregate across all namespaces; update the code to
restrict that subquery to the request namespace by passing the namespace into
the predicate (or applying ledgertransactiondb.Namespace(input.Namespace) to the
predicate) so the generated IN(...) uses a WHERE namespace = input.Namespace
filter; modify the calls at the two locations that invoke
ledgerTransactionCreditMovementPredicate (the shown block and the later 476-534
block) to supply input.Namespace (or to wrap the returned pred with
ledgertransactiondb.Namespace(input.Namespace)) so the DB work is tenant-scoped.
🧹 Nitpick comments (13)
api/v3/filters/parse_test.go (1)

29-29: 💤 Low value

Nice test coverage! Consider adding an empty value test case.

The tests cover the happy path, operator rejection, and invalid datetime well. One edge case that's missing: parseTextUnmarshalerPtr explicitly rejects empty values with a specific error message. Adding a quick test would complete the coverage:

🧪 Suggested test case
 	t.Run("invalid datetime rejected", func(t *testing.T) {
 		var f testFilter
 		err := Parse(url.Values{"filter[as_of]": {"not-a-date"}}, &f)
 		assert.ErrorIs(t, err, ErrInvalidDateTime)
 	})
+
+	t.Run("empty value rejected", func(t *testing.T) {
+		var f testFilter
+		err := Parse(url.Values{"filter[as_of]": {""}}, &f)
+		require.Error(t, err)
+		assert.Contains(t, err.Error(), "empty value")
+	})
 }

Also applies to: 322-342

🤖 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 `@api/v3/filters/parse_test.go` at line 29, Add a unit test that covers the
empty-value edge case for pointer unmarshaling: call the same test helper used
in parse_test.go but supply an empty string for the AsOf field (which is a
*time.Time) and assert that parseTextUnmarshalerPtr returns the specific
rejection error message (the exact error text returned by
parseTextUnmarshalerPtr). Update both places noted in the review (the existing
table-driven tests and the block around the other tests) to include this case so
the suite verifies empty input is rejected consistently.
api/spec/packages/aip/src/customers/credits/operations.tsp (1)

155-161: 💤 Low value

Use plain @query for the scalar DateTime parameter.

The deepObject style is for object types (e.g., filter[currency][eq]=USD). DateTime is a scalar, so it should use plain @query like other datetime params in the codebase:

`@query`
timestamp?: Shared.DateTime,

This aligns with OpenAPI standards and other DateTime query parameters throughout the API (e.g., in the legacy package). Run make gen-api after the change to confirm the OpenAPI spec reflects the correct serialization.

🤖 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 `@api/spec/packages/aip/src/customers/credits/operations.tsp` around lines 155
- 161, The timestamp query parameter is annotated with `@query`(#{ style:
"deepObject", explode: true }) but DateTime is a scalar and must use a plain
`@query`; update the timestamp parameter (the timestamp?: Shared.DateTime
property) to use simple `@query` (remove the deepObject/explode options), then run
`make gen-api` to regenerate and confirm the OpenAPI spec serializes the
DateTime as a normal scalar query parameter.
openmeter/ledger/breakage/README.md (2)

11-17: 💤 Low value

Minor style suggestion: vary sentence structure.

The static analysis tool noticed several successive sentences starting with the same pattern. Consider rephrasing for better flow:

  • Lines 11-12: "The ledger is... Breakage records are..."
  • Lines 14-17: "- plan means... - release means... - reopen means... - breakage impact means..."

This is purely stylistic—the content is clear and accurate.

🤖 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/README.md` around lines 11 - 17, Vary the sentence
openings and phrasing in the README section describing breakage: instead of
repeating "The ledger is..." and "Breakage records are..." reword one or both
lines (referencing r.priority, `@T`, E) to use alternatives like "Ledger entries
use..." or "Breakage entries represent..."; likewise rephrase the list items for
plan, release, reopen, and breakage impact by starting with verbs or short
clauses (e.g., "Plan: pre-books future breakage...", "Release: reduces planned
breakage...", "Reopen: increases planned breakage...", "Breakage impact: the
customer-visible expired amount...") so the sentences read with varied structure
while preserving the original meanings and symbols.

279-296: ⚡ Quick win

Clarify implemented vs. reserved semantics for credit purchase corrections.

Lines 296 state that "full credit-purchase correction semantics are not implemented yet," but the section above describes the intended behavior in detail.

Consider adding a brief note upfront indicating which specific operations ARE supported today (if any) versus what remains to be built, so readers don't assume the described behavior is fully working.

🤖 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/README.md` around lines 279 - 296, Add a short
upfront clarifying sentence to the credit purchase corrections section that
explicitly enumerates which operations are implemented today versus which are
reserved; mention that only issuance-like behavior (e.g., creating plans on
restore and booking releases on removing issued expiring credit shown by the
entries with FBO(route), RECEIVABLE/OTHER, and the plan.expires_at
[breakage.release] block) is documented as intended but that full
"credit-purchase correction" semantics (correction/delete policy, removable
amount checks, and consumed-credit behavior) are reserved/unimplemented; keep it
one concise sentence placed before the detailed example so readers won’t assume
the detailed behavior is already implemented.
openmeter/ledger/breakage/adapter/adapter.go (1)

19-25: ⚡ Quick win

Align Config.Validate() with the repo’s standard validation pattern.

Could you switch this to aggregated validation + models.NewNillableGenericValidationError(errors.Join(errs...)) so it stays consistent with other Validate() methods in openmeter/**.

Suggested change
 import (
 	"context"
 	"database/sql"
 	"errors"
-	"fmt"
+	"fmt"
 
 	entdb "github.com/openmeterio/openmeter/openmeter/ent/db"
 	"github.com/openmeterio/openmeter/openmeter/ledger/breakage"
 	"github.com/openmeterio/openmeter/pkg/framework/entutils"
 	"github.com/openmeterio/openmeter/pkg/framework/transaction"
+	"github.com/openmeterio/openmeter/pkg/models"
 )
@@
 func (c Config) Validate() error {
+	var errs []error
+
 	if c.Client == nil {
-		return errors.New("ent client is required")
+		errs = append(errs, errors.New("ent client is required"))
 	}
 
-	return nil
+	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/adapter/adapter.go` around lines 19 - 25, Replace
the single-return check in Config.Validate() with the repo-standard aggregated
validation pattern: create var errs []error, append an error to errs when
c.Client == nil (e.g., errors.New("ent client is required")), then return
models.NewNillableGenericValidationError(errors.Join(errs...)) so the method
collects all issues instead of returning early; keep the function name
Config.Validate and ensure you import/use errors.Join and
models.NewNillableGenericValidationError.
openmeter/ledger/customerbalance/transactions_test.go (1)

56-56: ⚡ Quick win

Use the repo-standard decimal assertion style here.

Nice test addition — just switch this assertion to the standard InexactFloat64() pattern for consistency across tests.

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 tests, prefer require.Equal(t, expectedFloat64, actual.InexactFloat64()) over boolean assertions, and use simple float64 literals over verbose decimal construction”.

🤖 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 assertion using
item.Amount.Equal(alpacadecimal.NewFromInt(-15)) with the repo-standard pattern:
call item.Amount.InexactFloat64() and assert it equals a simple float64 literal
using require.Equal(t, -15.0, ...); in other words, locate the assertion that
references item.Amount.Equal and alpacadecimal.NewFromInt(-15) in
transactions_test.go and change it to require.Equal with the InexactFloat64()
result.
openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity_test.go (1)

317-317: ⚡ Quick win

Use the test context here instead of context.Background().

Small tweak: bind this call chain to the suite test lifecycle with s.T().Context().

Suggested change
-	ctx := context.Background()
+	ctx := s.T().Context()

As per coding guidelines: **/*_test.go: Use t.Context() in tests when a testing.T or testing.TB is available instead of introducing context.Background() to keep cancellation and lifecycle tied to the test harness.

🤖 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 use of context.Background() with the test-bound context
to tie cancellation to the test lifecycle: change the ctx variable assignment
(ctx := context.Background()) in the funded credit activity test to use the
suite test context via s.T().Context() so that the test's context is bound to
the testing.T lifecycle; locate the ctx declaration in the test function where s
is the suite instance and update it accordingly.
tools/migrate/migrations/20260517121831_add_credit_expiration_breakage.up.sql (1)

31-32: ⚡ Quick win

Drop the redundant unique index on id.

id is already the primary key, so this extra unique index duplicates enforcement and index maintenance cost.

🤖 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/20260517121831_add_credit_expiration_breakage.up.sql`
around lines 31 - 32, Remove the redundant unique index creation for the primary
key: delete the CREATE UNIQUE INDEX "ledgerbreakagerecord_id" ON
"ledger_breakage_records" ("id"); statement (which creates index
ledgerbreakagerecord_id on table ledger_breakage_records) from the migration so
you rely on the existing primary key index instead.
openmeter/ledger/customerbalance/facade_test.go (2)

204-204: ⚡ Quick win

Use clock.SetTime(...) for later time jumps after the initial freeze.

After the first FreezeTime+defer pair, these additional freezes can be replaced with SetTime to keep the freeze lifecycle simple and aligned with the guideline.

As per coding guidelines: **/*_test.go: When using clock.FreezeTime(...) in tests, immediately pair it with defer clock.UnFreeze() in the same scope to prevent frozen time leaking to later assertions or subtests.

Also applies to: 212-212, 235-235

🤖 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` at line 204, Tests currently
call clock.FreezeTime(...) multiple times (e.g., clock.FreezeTime(beforeExpiry))
without pairing each freeze with a defer clock.UnFreeze(), causing fragile
freeze lifecycle; change subsequent freezes after the initial FreezeTime+defer
pair to clock.SetTime(...) instead (use clock.UnFreeze() only for the initial
FreezeTime call), so update occurrences of clock.FreezeTime(...) in the test
(and replace later ones with clock.SetTime(...)) and ensure the initial
FreezeTime has a matching defer clock.UnFreeze() in the same scope.

194-194: ⚡ Quick win

Prefer float-based require.Equal for alpacadecimal assertions in tests.

These assertions currently use boolean equality checks; please switch to InexactFloat64() comparisons for consistency with the test style guide.

As per coding guidelines: **/*_test.go: When asserting alpacadecimal.Decimal equality in tests, prefer require.Equal(t, expectedFloat64, actual.InexactFloat64()) over boolean assertions, and use simple float64 literals over verbose decimal construction.

Also applies to: 202-202, 210-210, 218-218, 245-245, 252-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` at line 194, Replace boolean
equality assertions that call alpacadecimal.Decimal.Equal with float-based
assertions using InexactFloat64(); e.g., change require.True(t,
balanceBeforeExpiry.Equal(amount)) to require.Equal(t, <expectedFloat64>,
balanceBeforeExpiry.InexactFloat64()), using a simple float64 literal for the
expected value instead of constructing a Decimal. Do the same for the other
listed occurrences (the assertions around variables like balanceBeforeExpiry,
amount and similar Decimal values) so all Decimal comparisons in facade_test.go
use require.Equal(t, expectedFloat64, actual.InexactFloat64()).
openmeter/ledger/chargeadapter/creditpurchase_test.go (1)

108-109: ⚡ Quick win

Please align these decimal assertions with the project’s test convention.

For these new checks, prefer require.Equal(t, expectedFloat64, actual.InexactFloat64()) instead of require.True(decimal.Equal(...)).

As per coding guidelines: When asserting alpacadecimal.Decimal equality in tests, prefer require.Equal(t, expectedFloat64, actual.InexactFloat64()) over boolean assertions.

Also applies to: 113-117, 146-154

🤖 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, The tests in creditpurchase_test.go use boolean decimal equality checks
(e.g., require.True(t, rows[0].Amount.Equal(...))) — update these to follow the
project convention by asserting the decimal value via InexactFloat64; for each
assertion referencing alpacadecimal.Decimal (such as rows[0].Amount and any
other alpacadecimal.Decimal checks around the cited ranges) replace
require.True(...Equal(...)) with require.Equal(t, expectedFloat64,
actual.InexactFloat64()) and similarly replace other decimal boolean assertions
in the file (including the blocks around lines 113-117 and 146-154) to use
require.Equal with the decimal's InexactFloat64() result.
openmeter/ledger/impact_test.go (1)

294-294: ⚡ Quick win

Use the repo’s preferred decimal assertion style here.

Please switch this to require.Equal(t, expectedFloat64, actual.InexactFloat64()) instead of require.True(...Equal(...)) to match the test convention.

As per coding guidelines: When asserting alpacadecimal.Decimal equality in tests, prefer require.Equal(t, expectedFloat64, actual.InexactFloat64()) over boolean assertions.

🤖 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, Replace the boolean decimal
equality assertion with the preferred float assertion: instead of
require.True(t, tt.want.Equal(ledger.TransactionImpact(tx, tt.filter))), call
require.Equal(t, tt.want.InexactFloat64(), ledger.TransactionImpact(tx,
tt.filter).InexactFloat64()) (or compute actual := ledger.TransactionImpact(tx,
tt.filter) and assert require.Equal(t, tt.want.InexactFloat64(),
actual.InexactFloat64())). This updates the assertion style for
alpacadecimal.Decimal to use InexactFloat64().
openmeter/ledger/breakage/adapter/record.go (1)

149-190: 💤 Low value

Consider whether ForUpdate() is intentionally omitted here.

Unlike ListReleaseRecords and ListCandidateRecords, this query doesn't use ForUpdate(). If this is a deliberate choice (e.g., read-only use case where locking isn't needed), that's fine. Just wanted to flag the inconsistency in case it was overlooked.

🤖 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/adapter/record.go` around lines 149 - 190,
ListExpiredRecords currently omits ForUpdate() while ListReleaseRecords and
ListCandidateRecords use it; decide whether row-level locking is required and
either add ForUpdate() to the query or document the deliberate omission. If
locking is intended, insert .ForUpdate() on the LedgerBreakageRecord query
(tx.db.LedgerBreakageRecord.Query().Where(predicates...).ForUpdate()...) before
ordering/All(ctx) so it matches the behavior of
ListReleaseRecords/ListCandidateRecords; otherwise add a comment in
ListExpiredRecords explaining why ForUpdate() is intentionally not used and
update any related tests or callers accordingly.
🤖 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/breakage/breakage_impacts.go`:
- Around line 17-55: The Validate method for ListExpiredBreakageImpactsInput
currently returns errors.Join(errs...) directly; change the return to wrap the
joined errors using the project-standard error type by returning
models.NewNillableGenericValidationError(errors.Join(errs...)) from
ListExpiredBreakageImpactsInput.Validate so the validation follows the codebase
guideline for Validate() error methods.

In `@openmeter/ledger/breakage/service.go`:
- Around line 64-80: The Validate() methods in this file currently return raw
errors.Join(errs...) — update each Validate() (including the one on Config and
the other Validate() functions referenced around lines 111-151, 162-196,
206-244, 246-274) to wrap the joined error using the repo-standard wrapper:
return models.NewNillableGenericValidationError(errors.Join(errs...)). Locate
the Validate functions by their names (e.g., Config.Validate) and replace the
final return value so all validation methods return
models.NewNillableGenericValidationError(errors.Join(errs...)) instead of
errors.Join(errs...).
- Around line 189-193: The validation must enforce that SourceEntryIdentityKey
is non-empty for usage-driven release kinds: when checking i.SourceKind in
ReleasePlanInput.Validate (the switch handling SourceKindUsage,
SourceKindUsageCorrection, SourceKindCreditPurchaseCorrection, and
SourceKindAdvanceBackfill), add a check that i.SourceEntryIdentityKey is present
and append an error if it's empty; update the same validation logic in the other
occurrences that validate release records (the other switch blocks handling
those same SourceKind values) so those paths also reject empty
SourceEntryIdentityKey rather than allowing the release row to persist without
source linkage.

In `@openmeter/ledger/breakage/types.go`:
- Around line 182-242: The Record.Validate() function currently returns
errors.Join(errs...) directly; change its final return to wrap the joined errors
with models.NewNillableGenericValidationError(errors.Join(errs...)) so the
API/domain validation uses the repo's standard wrapper (update the return in
Record.Validate). Also ensure the models package is imported if not already
present. Ensure behavior when errs is empty still yields the expected
nil/empty-wrapped result per models.NewNillableGenericValidationError.
- Around line 172-180: The CreateRecordsInput.Validate currently returns on the
first record error; change it to accumulate all record validation errors by
creating a slice var errs []error, append fmt.Errorf("records[%d]: %w", idx,
err) for each record.Validate() failure, and after the loop return
models.NewNillableGenericValidationError(errors.Join(errs...)) when errs is
non-empty (or nil when empty) instead of an immediate return; reference
CreateRecordsInput.Validate and record.Validate to locate the change and use
errors.Join and models.NewNillableGenericValidationError for the final
aggregated error.

In `@openmeter/ledger/collector/service.go`:
- Around line 65-87: NewService currently fails to validate config.Breakage so a
nil Breakage can be injected into accrualCollector and accrualCorrector; add a
check in NewService that returns an error (e.g., "breakage is required") when
config.Breakage == nil, analogous to the existing checks for TransactionManager
and AccountLocker, before constructing the service and assigning Breakage to the
accrualCollector and accrualCorrector fields.

In `@openmeter/ledger/customerbalance/README.md`:
- Line 135: The phrase "Customerbalance should show one net expired row:" is a
wording inconsistency; update the README text to use "Customer balance" instead
of "Customerbalance" (search for the exact string "Customerbalance should show
one net expired row:" and change it to "Customer balance should show one net
expired row:") so the term matches the rest of the docs.

In `@openmeter/ledger/customerbalance/transactions.go`:
- Around line 258-260: The mapping currently sets Type solely via
creditTransactionType(fboImpact) (and analogous debit mapping at the other
block), which ignores incoming CreditTransactionTypeExpired and never emits
"expired"; update the transaction-type derivation so it first checks for
breakage/template annotations or explicit incoming types (e.g., detect
CreditTransactionTypeExpired, plan/reopen/release flags) and return
CreditTransactionTypeExpired when present, and only if none apply fall back to
the existing sign-based logic in creditTransactionType (and the corresponding
debit mapping at the other block). Ensure the Type field assignment uses this
updated function and that any tests/consumers expecting expired rows are
covered.
- Around line 172-174: The running balance seed query drops the AsOf timestamp
and can include future entries; update the s.GetBalance call that builds
BalanceQuery (used to compute runningBalance) to include the same AsOf used to
load the list (e.g. set BalanceQuery.AsOf = lo.ToPtr(items[0].AsOf) or the
request's AsOf), so the balance seed honors the historical as-of view; keep the
existing Before/After fields (creditTransactionCursor(items[0])) and
Currency/CustomerID unchanged.

In `@openmeter/ledger/primitives.go`:
- Around line 266-271: ListTransactionsInput.Validate() currently returns early
when i.AsOf is present but zero; instead, follow the repo Validate() contract by
collecting this into the errs slice (e.g., append(errs,
ErrListTransactionsInputInvalid.WithAttrs(models.Attributes{"reason":"as_of_invalid","as_of":
i.AsOf})) ) rather than returning immediately, ensure there is a var errs
[]error at the top and that all other field checks append to errs as well, and
at the end return models.NewNillableGenericValidationError(errors.Join(errs...))
(or nil if errs is empty).

In `@openmeter/ledger/query.go`:
- Around line 74-86: The Validate() implementation must stop returning early and
instead collect all field errors into a slice (e.g., var errs []error); for each
failing check (the as_of zero check for p.Filters.AsOf and the mutual-exclusive
After/AsOf check for p.Filters.After && p.Filters.AsOf) append the corresponding
ErrLedgerQueryInvalid.WithAttrs(...) error into errs, and at the end return
models.NewNillableGenericValidationError(errors.Join(errs...)) (or nil when errs
is empty); update the Validate() method to reference p.Filters.AsOf,
p.Filters.After and ErrLedgerQueryInvalid and use errors.Join to aggregate
rather than immediate returns.

In `@openmeter/ledger/transactions/breakage.go`:
- Around line 21-51: The validate method on breakageTemplateBase currently
returns on the first error; change it to aggregate all validation issues into a
slice (e.g., var errs []error), append errors for each failing check (At.IsZero,
ledger.ValidateTransactionAmount(t.Amount), nil checks and account type/currency
mismatches for FBOAddress and BreakageAddress), and at the end return
models.NewNillableGenericValidationError(errors.Join(errs...)) (or nil if errs
is empty); update the other mentioned validate blocks (the checks at lines
~76-78, ~109-111, ~142-144) to follow the same pattern and reference
ledger.ValidateTransactionAmount, t.At, t.FBOAddress, t.BreakageAddress, and the
account type/currency checks when building errs.

In `@test/credits/sanity_test.go`:
- Around line 1138-1183: The helper createAndAdvanceCreditOnlyFlatFeeCharge
calls clock.FreezeTime(input.createAt) (and later
clock.FreezeTime(input.advanceAt)) without unfreezing, which can leak frozen
time; update the function to immediately pair each FreezeTime call with a defer
clock.UnFreeze() in the same scope (i.e., right after calling clock.FreezeTime
in createAndAdvanceCreditOnlyFlatFeeCharge) so time is always restored when the
helper returns, ensuring no test-time leakage across callers.

---

Outside diff comments:
In `@openmeter/ledger/historical/adapter/ledger.go`:
- Around line 341-347: The credit-movement subquery built by
ledgerTransactionCreditMovementPredicate is currently unscoped and can aggregate
across all namespaces; update the code to restrict that subquery to the request
namespace by passing the namespace into the predicate (or applying
ledgertransactiondb.Namespace(input.Namespace) to the predicate) so the
generated IN(...) uses a WHERE namespace = input.Namespace filter; modify the
calls at the two locations that invoke ledgerTransactionCreditMovementPredicate
(the shown block and the later 476-534 block) to supply input.Namespace (or to
wrap the returned pred with ledgertransactiondb.Namespace(input.Namespace)) so
the DB work is tenant-scoped.

---

Nitpick comments:
In `@api/spec/packages/aip/src/customers/credits/operations.tsp`:
- Around line 155-161: The timestamp query parameter is annotated with `@query`(#{
style: "deepObject", explode: true }) but DateTime is a scalar and must use a
plain `@query`; update the timestamp parameter (the timestamp?: Shared.DateTime
property) to use simple `@query` (remove the deepObject/explode options), then run
`make gen-api` to regenerate and confirm the OpenAPI spec serializes the
DateTime as a normal scalar query parameter.

In `@api/v3/filters/parse_test.go`:
- Line 29: Add a unit test that covers the empty-value edge case for pointer
unmarshaling: call the same test helper used in parse_test.go but supply an
empty string for the AsOf field (which is a *time.Time) and assert that
parseTextUnmarshalerPtr returns the specific rejection error message (the exact
error text returned by parseTextUnmarshalerPtr). Update both places noted in the
review (the existing table-driven tests and the block around the other tests) to
include this case so the suite verifies empty input is rejected consistently.

In
`@openmeter/billing/charges/creditpurchase/adapter/funded_credit_activity_test.go`:
- Line 317: Replace the use of context.Background() with the test-bound context
to tie cancellation to the test lifecycle: change the ctx variable assignment
(ctx := context.Background()) in the funded credit activity test to use the
suite test context via s.T().Context() so that the test's context is bound to
the testing.T lifecycle; locate the ctx declaration in the test function where s
is the suite instance and update it accordingly.

In `@openmeter/ledger/breakage/adapter/adapter.go`:
- Around line 19-25: Replace the single-return check in Config.Validate() with
the repo-standard aggregated validation pattern: create var errs []error, append
an error to errs when c.Client == nil (e.g., errors.New("ent client is
required")), then return
models.NewNillableGenericValidationError(errors.Join(errs...)) so the method
collects all issues instead of returning early; keep the function name
Config.Validate and ensure you import/use errors.Join and
models.NewNillableGenericValidationError.

In `@openmeter/ledger/breakage/adapter/record.go`:
- Around line 149-190: ListExpiredRecords currently omits ForUpdate() while
ListReleaseRecords and ListCandidateRecords use it; decide whether row-level
locking is required and either add ForUpdate() to the query or document the
deliberate omission. If locking is intended, insert .ForUpdate() on the
LedgerBreakageRecord query
(tx.db.LedgerBreakageRecord.Query().Where(predicates...).ForUpdate()...) before
ordering/All(ctx) so it matches the behavior of
ListReleaseRecords/ListCandidateRecords; otherwise add a comment in
ListExpiredRecords explaining why ForUpdate() is intentionally not used and
update any related tests or callers accordingly.

In `@openmeter/ledger/breakage/README.md`:
- Around line 11-17: Vary the sentence openings and phrasing in the README
section describing breakage: instead of repeating "The ledger is..." and
"Breakage records are..." reword one or both lines (referencing r.priority, `@T`,
E) to use alternatives like "Ledger entries use..." or "Breakage entries
represent..."; likewise rephrase the list items for plan, release, reopen, and
breakage impact by starting with verbs or short clauses (e.g., "Plan: pre-books
future breakage...", "Release: reduces planned breakage...", "Reopen: increases
planned breakage...", "Breakage impact: the customer-visible expired amount...")
so the sentences read with varied structure while preserving the original
meanings and symbols.
- Around line 279-296: Add a short upfront clarifying sentence to the credit
purchase corrections section that explicitly enumerates which operations are
implemented today versus which are reserved; mention that only issuance-like
behavior (e.g., creating plans on restore and booking releases on removing
issued expiring credit shown by the entries with FBO(route), RECEIVABLE/OTHER,
and the plan.expires_at [breakage.release] block) is documented as intended but
that full "credit-purchase correction" semantics (correction/delete policy,
removable amount checks, and consumed-credit behavior) are
reserved/unimplemented; keep it one concise sentence placed before the detailed
example so readers won’t assume the detailed behavior is already implemented.

In `@openmeter/ledger/chargeadapter/creditpurchase_test.go`:
- Around line 108-109: The tests in creditpurchase_test.go use boolean decimal
equality checks (e.g., require.True(t, rows[0].Amount.Equal(...))) — update
these to follow the project convention by asserting the decimal value via
InexactFloat64; for each assertion referencing alpacadecimal.Decimal (such as
rows[0].Amount and any other alpacadecimal.Decimal checks around the cited
ranges) replace require.True(...Equal(...)) with require.Equal(t,
expectedFloat64, actual.InexactFloat64()) and similarly replace other decimal
boolean assertions in the file (including the blocks around lines 113-117 and
146-154) to use require.Equal with the decimal's InexactFloat64() result.

In `@openmeter/ledger/customerbalance/facade_test.go`:
- Line 204: Tests currently call clock.FreezeTime(...) multiple times (e.g.,
clock.FreezeTime(beforeExpiry)) without pairing each freeze with a defer
clock.UnFreeze(), causing fragile freeze lifecycle; change subsequent freezes
after the initial FreezeTime+defer pair to clock.SetTime(...) instead (use
clock.UnFreeze() only for the initial FreezeTime call), so update occurrences of
clock.FreezeTime(...) in the test (and replace later ones with
clock.SetTime(...)) and ensure the initial FreezeTime has a matching defer
clock.UnFreeze() in the same scope.
- Line 194: Replace boolean equality assertions that call
alpacadecimal.Decimal.Equal with float-based assertions using InexactFloat64();
e.g., change require.True(t, balanceBeforeExpiry.Equal(amount)) to
require.Equal(t, <expectedFloat64>, balanceBeforeExpiry.InexactFloat64()), using
a simple float64 literal for the expected value instead of constructing a
Decimal. Do the same for the other listed occurrences (the assertions around
variables like balanceBeforeExpiry, amount and similar Decimal values) so all
Decimal comparisons in facade_test.go use require.Equal(t, expectedFloat64,
actual.InexactFloat64()).

In `@openmeter/ledger/customerbalance/transactions_test.go`:
- Line 56: Replace the boolean decimal equality assertion using
item.Amount.Equal(alpacadecimal.NewFromInt(-15)) with the repo-standard pattern:
call item.Amount.InexactFloat64() and assert it equals a simple float64 literal
using require.Equal(t, -15.0, ...); in other words, locate the assertion that
references item.Amount.Equal and alpacadecimal.NewFromInt(-15) in
transactions_test.go and change it to require.Equal with the InexactFloat64()
result.

In `@openmeter/ledger/impact_test.go`:
- Line 294: Replace the boolean decimal equality assertion with the preferred
float assertion: instead of require.True(t,
tt.want.Equal(ledger.TransactionImpact(tx, tt.filter))), call require.Equal(t,
tt.want.InexactFloat64(), ledger.TransactionImpact(tx,
tt.filter).InexactFloat64()) (or compute actual := ledger.TransactionImpact(tx,
tt.filter) and assert require.Equal(t, tt.want.InexactFloat64(),
actual.InexactFloat64())). This updates the assertion style for
alpacadecimal.Decimal to use InexactFloat64().

In
`@tools/migrate/migrations/20260517121831_add_credit_expiration_breakage.up.sql`:
- Around line 31-32: Remove the redundant unique index creation for the primary
key: delete the CREATE UNIQUE INDEX "ledgerbreakagerecord_id" ON
"ledger_breakage_records" ("id"); statement (which creates index
ledgerbreakagerecord_id on table ledger_breakage_records) from the migration so
you rely on the existing primary key index instead.
🪄 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: e2dd525a-fe32-4d0c-8076-407af4071d4d

📥 Commits

Reviewing files that changed from the base of the PR and between f20774b and a954966.

⛔ Files ignored due to path filters (31)
  • api/v3/openapi.yaml is excluded by !**/openapi.yaml
  • 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

Comment on lines +17 to +55
func (i ListExpiredBreakageImpactsInput) Validate() error {
var errs []error

if err := i.CustomerID.Validate(); err != nil {
errs = append(errs, fmt.Errorf("customer id: %w", err))
}

if i.Currency != nil {
if err := i.Currency.Validate(); err != nil {
errs = append(errs, fmt.Errorf("currency: %w", err))
}
}

if i.AsOf.IsZero() {
errs = append(errs, errors.New("as of is required"))
}

if i.After != nil {
if err := i.After.Validate(); err != nil {
errs = append(errs, fmt.Errorf("after: %w", err))
}
}

if i.Before != nil {
if err := i.Before.Validate(); err != nil {
errs = append(errs, fmt.Errorf("before: %w", err))
}
}

if i.After != nil && i.Before != nil {
errs = append(errs, errors.New("after and before cannot be set together"))
}

if i.Limit < 1 {
errs = append(errs, errors.New("limit must be greater than 0"))
}

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 | 🟡 Minor | ⚡ Quick win

Validation return pattern doesn't match the codebase guideline.

Per the coding guidelines for openmeter/**/*.go, Validate() error methods should return models.NewNillableGenericValidationError(errors.Join(errs...)) rather than errors.Join(errs...) directly. This ensures consistent error typing across the codebase.

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` around lines 17 - 55, The
Validate method for ListExpiredBreakageImpactsInput currently returns
errors.Join(errs...) directly; change the return to wrap the joined errors using
the project-standard error type by returning
models.NewNillableGenericValidationError(errors.Join(errs...)) from
ListExpiredBreakageImpactsInput.Validate so the validation follows the codebase
guideline for Validate() error methods.

Comment on lines +64 to +80
func (c Config) Validate() error {
var errs []error

if c.Adapter == nil {
errs = append(errs, errors.New("adapter is required"))
}

if c.Dependencies.AccountService == nil {
errs = append(errs, errors.New("account service is required"))
}

if c.Dependencies.AccountCatalog == nil {
errs = append(errs, errors.New("account catalog is required"))
}

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.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Use the repo-standard validation error wrapper in Validate() methods

These Validate() methods currently return raw errors.Join(...). In this repo, they should wrap joined errors with models.NewNillableGenericValidationError(...) for consistent API/domain error behavior.

Suggested pattern
 func (c Config) Validate() error {
 	var errs []error
@@
-	return errors.Join(errs...)
+	return models.NewNillableGenericValidationError(errors.Join(errs...))
 }

Apply the same pattern to all Validate() error methods in this file.

As per coding guidelines "openmeter/**/*.go: 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".

Also applies to: 111-151, 162-196, 206-244, 246-274

🤖 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 64 - 80, The Validate()
methods in this file currently return raw errors.Join(errs...) — update each
Validate() (including the one on Config and the other Validate() functions
referenced around lines 111-151, 162-196, 206-244, 246-274) to wrap the joined
error using the repo-standard wrapper: return
models.NewNillableGenericValidationError(errors.Join(errs...)). Locate the
Validate functions by their names (e.g., Config.Validate) and replace the final
return value so all validation methods return
models.NewNillableGenericValidationError(errors.Join(errs...)) instead of
errors.Join(errs...).

Comment on lines +189 to +193
switch i.SourceKind {
case SourceKindUsage, SourceKindUsageCorrection, SourceKindCreditPurchaseCorrection, SourceKindAdvanceBackfill:
default:
errs = append(errs, fmt.Errorf("invalid release source kind: %s", i.SourceKind))
}

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 source entry identity for usage-driven release records

For SourceKindUsage, SourceKindUsageCorrection, and SourceKindCreditPurchaseCorrection, SourceEntryIdentityKey should be required in ReleasePlanInput.Validate(). Right now an empty key passes validation and can persist a release row without source linkage.

Suggested fix
 	switch i.SourceKind {
 	case SourceKindUsage, SourceKindUsageCorrection, SourceKindCreditPurchaseCorrection, SourceKindAdvanceBackfill:
 	default:
 		errs = append(errs, fmt.Errorf("invalid release source kind: %s", i.SourceKind))
 	}
+
+	if i.SourceKind != SourceKindAdvanceBackfill && i.SourceEntryIdentityKey == "" {
+		errs = append(errs, errors.New("source entry identity key is required for this release source kind"))
+	}

Also applies to: 362-363, 578-588

🤖 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 189 - 193, The validation
must enforce that SourceEntryIdentityKey is non-empty for usage-driven release
kinds: when checking i.SourceKind in ReleasePlanInput.Validate (the switch
handling SourceKindUsage, SourceKindUsageCorrection,
SourceKindCreditPurchaseCorrection, and SourceKindAdvanceBackfill), add a check
that i.SourceEntryIdentityKey is present and append an error if it's empty;
update the same validation logic in the other occurrences that validate release
records (the other switch blocks handling those same SourceKind values) so those
paths also reject empty SourceEntryIdentityKey rather than allowing the release
row to persist without source linkage.

Comment on lines +172 to +180
func (i CreateRecordsInput) Validate() error {
for idx, record := range i.Records {
if err := record.Validate(); err != nil {
return fmt.Errorf("records[%d]: %w", idx, err)
}
}

return nil
}

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.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Aggregate all record validation errors in CreateRecordsInput.Validate.

Right now Line 175 returns on the first invalid record. This drops later validation issues in batch inputs. Collect all record errors and return once at the end via the project’s nillable validation wrapper.

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/types.go` around lines 172 - 180, The
CreateRecordsInput.Validate currently returns on the first record error; change
it to accumulate all record validation errors by creating a slice var errs
[]error, append fmt.Errorf("records[%d]: %w", idx, err) for each
record.Validate() failure, and after the loop return
models.NewNillableGenericValidationError(errors.Join(errs...)) when errs is
non-empty (or nil when empty) instead of an immediate return; reference
CreateRecordsInput.Validate and record.Validate to locate the change and use
errors.Join and models.NewNillableGenericValidationError for the final
aggregated error.

Comment on lines +182 to +242
func (c Record) Validate() error {
var errs []error

if err := c.ID.Validate(); err != nil {
errs = append(errs, fmt.Errorf("id: %w", err))
}

switch c.Kind {
case ledger.BreakageKindPlan, ledger.BreakageKindRelease, ledger.BreakageKindReopen:
default:
errs = append(errs, fmt.Errorf("invalid kind: %s", c.Kind))
}

if !c.Amount.IsPositive() {
errs = append(errs, errors.New("amount must be positive"))
}

if err := c.CustomerID.Validate(); err != nil {
errs = append(errs, fmt.Errorf("customer id: %w", err))
}

if err := c.Currency.Validate(); err != nil {
errs = append(errs, fmt.Errorf("currency: %w", err))
}

if err := ledger.ValidateCreditPriority(c.CreditPriority); err != nil {
errs = append(errs, fmt.Errorf("credit priority: %w", err))
}

if c.ExpiresAt.IsZero() {
errs = append(errs, errors.New("expires at is required"))
}

switch c.SourceKind {
case SourceKindCreditPurchase, SourceKindUsage, SourceKindUsageCorrection, SourceKindCreditPurchaseCorrection, SourceKindAdvanceBackfill:
default:
errs = append(errs, fmt.Errorf("invalid source kind: %s", c.SourceKind))
}

if c.BreakageTransactionGroupID == "" {
errs = append(errs, errors.New("breakage transaction group id is required"))
}

if c.BreakageTransactionID == "" {
errs = append(errs, errors.New("breakage transaction id is required"))
}

if c.FBOSubAccountID == "" {
errs = append(errs, errors.New("FBO sub-account id is required"))
}

if c.BreakageSubAccountID == "" {
errs = append(errs, errors.New("breakage sub-account id is required"))
}

if c.Kind != ledger.BreakageKindPlan && (c.PlanID == nil || *c.PlanID == "") {
errs = append(errs, errors.New("plan id is required"))
}

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.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Wrap Record.Validate result with models.NewNillableGenericValidationError(...).

Line 241 currently returns raw errors.Join(errs...). In this repo, validation methods should return the nillable generic validation error wrapper for consistency with API/domain error handling.

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/types.go` around lines 182 - 242, The
Record.Validate() function currently returns errors.Join(errs...) directly;
change its final return to wrap the joined errors with
models.NewNillableGenericValidationError(errors.Join(errs...)) so the API/domain
validation uses the repo's standard wrapper (update the return in
Record.Validate). Also ensure the models package is imported if not already
present. Ensure behavior when errs is empty still yields the expected
nil/empty-wrapped result per models.NewNillableGenericValidationError.

Comment on lines +258 to +260
Type: creditTransactionType(fboImpact),
Currency: currency,
Amount: fboImpact,

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

expired is validated but never emitted by transaction mapping.

CreditTransactionTypeExpired is accepted input, but current mapping derives type only from sign (funded/consumed), so breakage/expiration rows can’t be represented as expired.

Consider deriving type from breakage/template annotations first (e.g. plan/reopen/release semantics), then falling back to sign-based mapping for non-breakage transactions.

Also applies to: 303-309

🤖 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 258 - 260, The
mapping currently sets Type solely via creditTransactionType(fboImpact) (and
analogous debit mapping at the other block), which ignores incoming
CreditTransactionTypeExpired and never emits "expired"; update the
transaction-type derivation so it first checks for breakage/template annotations
or explicit incoming types (e.g., detect CreditTransactionTypeExpired,
plan/reopen/release flags) and return CreditTransactionTypeExpired when present,
and only if none apply fall back to the existing sign-based logic in
creditTransactionType (and the corresponding debit mapping at the other block).
Ensure the Type field assignment uses this updated function and that any
tests/consumers expecting expired rows are covered.

Comment on lines +266 to +271
if i.AsOf != nil && i.AsOf.IsZero() {
return ErrListTransactionsInputInvalid.WithAttrs(models.Attributes{
"reason": "as_of_invalid",
"as_of": i.AsOf,
})
}

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.

🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift

Please align ListTransactionsInput.Validate() to aggregated validation errors.

This adds another early-return branch; per the repo contract for Validate(), collect all issues in errs and return models.NewNillableGenericValidationError(errors.Join(errs...)) instead of returning on first hit.

As per coding guidelines: openmeter/**/*.go: 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/primitives.go` around lines 266 - 271,
ListTransactionsInput.Validate() currently returns early when i.AsOf is present
but zero; instead, follow the repo Validate() contract by collecting this into
the errs slice (e.g., append(errs,
ErrListTransactionsInputInvalid.WithAttrs(models.Attributes{"reason":"as_of_invalid","as_of":
i.AsOf})) ) rather than returning immediately, ensure there is a var errs
[]error at the top and that all other field checks append to errs as well, and
at the end return models.NewNillableGenericValidationError(errors.Join(errs...))
(or nil if errs is empty).

Comment thread openmeter/ledger/query.go
Comment on lines +74 to +86
if p.Filters.AsOf != nil && p.Filters.AsOf.IsZero() {
return ErrLedgerQueryInvalid.WithAttrs(models.Attributes{
"reason": "as_of_invalid",
"as_of": p.Filters.AsOf,
"error": fmt.Errorf("as_of must not be zero"),
})
}

if p.Filters.After != nil && p.Filters.AsOf != nil {
return ErrLedgerQueryInvalid.WithAttrs(models.Attributes{
"reason": "after_as_of_both_set",
})
}

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.

🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift

Please align Validate() with the repo’s aggregate-validation pattern.

These new as_of checks return immediately, but Validate() error methods here are expected to collect all validation errors and return a combined nillable validation error.

Suggested direction
 func (p Query) Validate() error {
+	var errs []error
 	...
-	if p.Filters.AsOf != nil && p.Filters.AsOf.IsZero() {
-		return ErrLedgerQueryInvalid.WithAttrs(models.Attributes{
+	if p.Filters.AsOf != nil && p.Filters.AsOf.IsZero() {
+		errs = append(errs, ErrLedgerQueryInvalid.WithAttrs(models.Attributes{
 			"reason": "as_of_invalid",
 			"as_of":  p.Filters.AsOf,
 			"error":  fmt.Errorf("as_of must not be zero"),
-		})
+		}))
 	}
 
 	if p.Filters.After != nil && p.Filters.AsOf != nil {
-		return ErrLedgerQueryInvalid.WithAttrs(models.Attributes{
+		errs = append(errs, ErrLedgerQueryInvalid.WithAttrs(models.Attributes{
 			"reason": "after_as_of_both_set",
-		})
+		}))
 	}
+	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”.

📝 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
if p.Filters.AsOf != nil && p.Filters.AsOf.IsZero() {
return ErrLedgerQueryInvalid.WithAttrs(models.Attributes{
"reason": "as_of_invalid",
"as_of": p.Filters.AsOf,
"error": fmt.Errorf("as_of must not be zero"),
})
}
if p.Filters.After != nil && p.Filters.AsOf != nil {
return ErrLedgerQueryInvalid.WithAttrs(models.Attributes{
"reason": "after_as_of_both_set",
})
}
if p.Filters.AsOf != nil && p.Filters.AsOf.IsZero() {
errs = append(errs, ErrLedgerQueryInvalid.WithAttrs(models.Attributes{
"reason": "as_of_invalid",
"as_of": p.Filters.AsOf,
"error": fmt.Errorf("as_of must not be zero"),
}))
}
if p.Filters.After != nil && p.Filters.AsOf != nil {
errs = append(errs, ErrLedgerQueryInvalid.WithAttats(models.Attributes{
"reason": "after_as_of_both_set",
}))
}
🤖 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/query.go` around lines 74 - 86, The Validate()
implementation must stop returning early and instead collect all field errors
into a slice (e.g., var errs []error); for each failing check (the as_of zero
check for p.Filters.AsOf and the mutual-exclusive After/AsOf check for
p.Filters.After && p.Filters.AsOf) append the corresponding
ErrLedgerQueryInvalid.WithAttrs(...) error into errs, and at the end return
models.NewNillableGenericValidationError(errors.Join(errs...)) (or nil when errs
is empty); update the Validate() method to reference p.Filters.AsOf,
p.Filters.After and ErrLedgerQueryInvalid and use errors.Join to aggregate
rather than immediate returns.

Comment on lines +21 to +51
func (t breakageTemplateBase) validate() error {
if t.At.IsZero() {
return fmt.Errorf("at is required")
}

if err := ledger.ValidateTransactionAmount(t.Amount); err != nil {
return fmt.Errorf("amount: %w", err)
}

if t.FBOAddress == nil {
return fmt.Errorf("FBO address is required")
}

if t.FBOAddress.AccountType() != ledger.AccountTypeCustomerFBO {
return fmt.Errorf("FBO address account type must be customer_fbo")
}

if t.BreakageAddress == nil {
return fmt.Errorf("breakage address is required")
}

if t.BreakageAddress.AccountType() != ledger.AccountTypeBreakage {
return fmt.Errorf("breakage address account type must be breakage")
}

if t.FBOAddress.Route().Route().Currency != t.BreakageAddress.Route().Route().Currency {
return fmt.Errorf("FBO and breakage currency must match")
}

return nil
}

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.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Please align Validate() with the repo’s aggregated-validation pattern.

Right now validation exits on first error. In this codebase, Validate() error methods should collect all field issues and return a nillable generic validation error wrapping errors.Join(...).

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.

Also applies to: 76-78, 109-111, 142-144

🤖 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/breakage.go` around lines 21 - 51, The validate
method on breakageTemplateBase currently returns on the first error; change it
to aggregate all validation issues into a slice (e.g., var errs []error), append
errors for each failing check (At.IsZero,
ledger.ValidateTransactionAmount(t.Amount), nil checks and account type/currency
mismatches for FBOAddress and BreakageAddress), and at the end return
models.NewNillableGenericValidationError(errors.Join(errs...)) (or nil if errs
is empty); update the other mentioned validate blocks (the checks at lines
~76-78, ~109-111, ~142-144) to follow the same pattern and reference
ledger.ValidateTransactionAmount, t.At, t.FBOAddress, t.BreakageAddress, and the
account type/currency checks when building errs.

Comment on lines +1138 to +1183
func (s *SanitySuite) createAndAdvanceCreditOnlyFlatFeeCharge(input createCreditOnlyFlatFeeChargeInput) createdCreditOnlyFlatFeeCharge {
s.T().Helper()

clock.FreezeTime(input.createAt)

res, err := s.Charges.Create(input.ctx, charges.CreateInput{
Namespace: input.namespace,
Intents: charges.ChargeIntents{
s.CreateMockChargeIntent(CreateMockChargeIntentInput{
Customer: input.customer,
Currency: USD,
ServicePeriod: input.servicePeriod,
SettlementMode: productcatalog.CreditOnlySettlementMode,
Price: productcatalog.NewPriceFrom(productcatalog.FlatPrice{
Amount: input.amount,
PaymentTerm: productcatalog.InAdvancePaymentTerm,
}),
Name: input.name,
ManagedBy: billing.SubscriptionManagedLine,
UniqueReferenceID: input.name,
}),
},
})
s.Require().NoError(err)
s.Require().Len(res, 1)

chargeID, err := res[0].GetChargeID()
s.NoError(err)

clock.FreezeTime(input.advanceAt)

advancedCharges, err := s.Charges.AdvanceCharges(input.ctx, charges.AdvanceChargesInput{
Customer: input.customer,
})
s.Require().NoError(err)
s.Require().Len(advancedCharges, 1)

charge, err := advancedCharges[0].AsFlatFeeCharge()
s.NoError(err)
s.Equal(flatfee.StatusFinal, charge.Status)

return createdCreditOnlyFlatFeeCharge{
id: chargeID.ID,
charge: charge,
}
}

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

Clock freeze leaks out of helper scope

Nice helper overall, but clock.FreezeTime(...) is called here without an immediate unfreeze in the same scope, so test-time can leak across callers and make scenarios order-sensitive.

Suggested fix
 func (s *SanitySuite) createAndAdvanceCreditOnlyFlatFeeCharge(input createCreditOnlyFlatFeeChargeInput) createdCreditOnlyFlatFeeCharge {
 	s.T().Helper()
 
 	clock.FreezeTime(input.createAt)
+	defer clock.UnFreeze()
 
 	res, err := s.Charges.Create(input.ctx, charges.CreateInput{
 		Namespace: input.namespace,
@@
 	clock.FreezeTime(input.advanceAt)

As per coding guidelines "**/*_test.go: When using clock.FreezeTime(...) in tests, immediately pair it with defer clock.UnFreeze() in the same scope to prevent frozen time leaking to later assertions or subtests".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/credits/sanity_test.go` around lines 1138 - 1183, The helper
createAndAdvanceCreditOnlyFlatFeeCharge calls clock.FreezeTime(input.createAt)
(and later clock.FreezeTime(input.advanceAt)) without unfreezing, which can leak
frozen time; update the function to immediately pair each FreezeTime call with a
defer clock.UnFreeze() in the same scope (i.e., right after calling
clock.FreezeTime in createAndAdvanceCreditOnlyFlatFeeCharge) so time is always
restored when the helper returns, ensuring no test-time leakage across callers.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/v3/filters/parse_test.go`:
- Around line 322-342: Add a subtest to TestParse_TimePtr to exercise duplicate
query parameters: call Parse with url.Values containing two values for
"filter[time_ptr]" (e.g. {"2026-05-11T10:30:00Z","2026-05-12T11:00:00Z"})
against the same testFilter and assert that the parser returns the expected
error (the same error class other tests use for repeated-parameter validation)
or otherwise rejects duplicates; locate the TestParse_TimePtr function and add
the new t.Run block referencing Parse, testFilter, and the TimePtr field to
mirror existing duplicate-parameter coverage in other type tests.
🪄 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: 42e03a6c-fbf4-4cfa-8a81-c10176d7b781

📥 Commits

Reviewing files that changed from the base of the PR and between a954966 and fc48236.

📒 Files selected for processing (2)
  • api/v3/filters/parse_test.go
  • e2e/customer_credits_v3_test.go

Comment on lines +322 to 342
func TestParse_TimePtr(t *testing.T) {
t.Run("simple datetime value", func(t *testing.T) {
var f testFilter
require.NoError(t, Parse(url.Values{"filter[time_ptr]": {"2026-05-11T10:30:00Z"}}, &f))
require.NotNil(t, f.TimePtr)
assert.Equal(t, time.Date(2026, 5, 11, 10, 30, 0, 0, time.UTC), *f.TimePtr)
})

t.Run("operator-style key rejected", func(t *testing.T) {
var f testFilter
err := Parse(url.Values{"filter[time_ptr][eq]": {"2026-05-11T10:30:00Z"}}, &f)
require.Error(t, err)
assert.Contains(t, err.Error(), "operator-style keys are not supported")
})

t.Run("invalid datetime rejected", func(t *testing.T) {
var f testFilter
err := Parse(url.Values{"filter[time_ptr]": {"not-a-date"}}, &f)
assert.ErrorIs(t, err, ErrInvalidDateTime)
})
}

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

Add duplicate-parameter coverage for time_ptr.

Nice additions here. One small gap: TestParse_TimePtr doesn’t check repeated query params (e.g. filter[time_ptr]=a&filter[time_ptr]=b), while other typed fields do. Adding that subtest would guard regression in the repeated-parameter validation path.

Suggested test addition
 func TestParse_TimePtr(t *testing.T) {
@@
 	t.Run("invalid datetime rejected", func(t *testing.T) {
 		var f testFilter
 		err := Parse(url.Values{"filter[time_ptr]": {"not-a-date"}}, &f)
 		assert.ErrorIs(t, err, ErrInvalidDateTime)
 	})
+
+	t.Run("duplicate time_ptr rejected", func(t *testing.T) {
+		var f testFilter
+		err := Parse(url.Values{"filter[time_ptr]": {"2026-05-11T10:30:00Z", "2026-05-11T11:30:00Z"}}, &f)
+		require.Error(t, err)
+		assert.Contains(t, err.Error(), "repeated query parameter")
+	})
 }

As per coding guidelines: "**/*_test.go: Make sure the tests are comprehensive and cover the changes."

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func TestParse_TimePtr(t *testing.T) {
t.Run("simple datetime value", func(t *testing.T) {
var f testFilter
require.NoError(t, Parse(url.Values{"filter[time_ptr]": {"2026-05-11T10:30:00Z"}}, &f))
require.NotNil(t, f.TimePtr)
assert.Equal(t, time.Date(2026, 5, 11, 10, 30, 0, 0, time.UTC), *f.TimePtr)
})
t.Run("operator-style key rejected", func(t *testing.T) {
var f testFilter
err := Parse(url.Values{"filter[time_ptr][eq]": {"2026-05-11T10:30:00Z"}}, &f)
require.Error(t, err)
assert.Contains(t, err.Error(), "operator-style keys are not supported")
})
t.Run("invalid datetime rejected", func(t *testing.T) {
var f testFilter
err := Parse(url.Values{"filter[time_ptr]": {"not-a-date"}}, &f)
assert.ErrorIs(t, err, ErrInvalidDateTime)
})
}
func TestParse_TimePtr(t *testing.T) {
t.Run("simple datetime value", func(t *testing.T) {
var f testFilter
require.NoError(t, Parse(url.Values{"filter[time_ptr]": {"2026-05-11T10:30:00Z"}}, &f))
require.NotNil(t, f.TimePtr)
assert.Equal(t, time.Date(2026, 5, 11, 10, 30, 0, 0, time.UTC), *f.TimePtr)
})
t.Run("operator-style key rejected", func(t *testing.T) {
var f testFilter
err := Parse(url.Values{"filter[time_ptr][eq]": {"2026-05-11T10:30:00Z"}}, &f)
require.Error(t, err)
assert.Contains(t, err.Error(), "operator-style keys are not supported")
})
t.Run("invalid datetime rejected", func(t *testing.T) {
var f testFilter
err := Parse(url.Values{"filter[time_ptr]": {"not-a-date"}}, &f)
assert.ErrorIs(t, err, ErrInvalidDateTime)
})
t.Run("duplicate time_ptr rejected", func(t *testing.T) {
var f testFilter
err := Parse(url.Values{"filter[time_ptr]": {"2026-05-11T10:30:00Z", "2026-05-11T11:30:00Z"}}, &f)
require.Error(t, err)
assert.Contains(t, err.Error(), "repeated query parameter")
})
}
🤖 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 `@api/v3/filters/parse_test.go` around lines 322 - 342, Add a subtest to
TestParse_TimePtr to exercise duplicate query parameters: call Parse with
url.Values containing two values for "filter[time_ptr]" (e.g.
{"2026-05-11T10:30:00Z","2026-05-12T11:00:00Z"}) against the same testFilter and
assert that the parser returns the expected error (the same error class other
tests use for repeated-parameter validation) or otherwise rejects duplicates;
locate the TestParse_TimePtr function and add the new t.Run block referencing
Parse, testFilter, and the TimePtr field to mirror existing duplicate-parameter
coverage in other type tests.

@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)
api/spec/packages/aip/src/customers/credits/operations.tsp (1)

140-140: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

This aligns with the existing backend implementation—no breaking change

Good catch on this change! The backend already expects StringFieldFilterExact for GetCreditBalanceParamsFilter.currency (confirmed in api/v3/api.gen.go), so this is a correction to the TypeSpec to match reality rather than a breaking change.

That said, worth a quick review: across this file you've got three different currency field types:

  • Line 31: Shared.CurrencyCode (ListCreditGrantsParamsFilter)
  • Line 140: Common.StringFieldFilterExact (GetCreditBalanceParamsFilter)
  • Line 181: Currencies.CurrencyCode (ListCreditTransactionsParamsFilter)

The filter wrapper approach for GetCreditBalance makes sense if it needs more flexible filtering than the other endpoints, but just double-check it's intentional!

The new timestamp parameter looks solid—using plain @query for the DateTime is correct, and the filter below correctly uses deepObject style for complex objects.

Remember to run make gen-api after merging to regenerate the OpenAPI spec and SDKs.

🤖 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 `@api/spec/packages/aip/src/customers/credits/operations.tsp` at line 140,
Update the TypeSpec so GetCreditBalanceParamsFilter.currency remains
Common.StringFieldFilterExact (as in the diff) and confirm the other two
currency fields—ListCreditGrantsParamsFilter.currency (Shared.CurrencyCode) and
ListCreditTransactionsParamsFilter.currency (Currencies.CurrencyCode)—are
intentionally different; if they should match, change those types to the
intended wrapper or code enum accordingly (refer to
ListCreditGrantsParamsFilter, GetCreditBalanceParamsFilter,
ListCreditTransactionsParamsFilter), then run make gen-api to regenerate the
OpenAPI spec and SDKs.
🤖 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 `@api/spec/packages/aip/src/customers/credits/operations.tsp`:
- Line 140: Update the TypeSpec so GetCreditBalanceParamsFilter.currency remains
Common.StringFieldFilterExact (as in the diff) and confirm the other two
currency fields—ListCreditGrantsParamsFilter.currency (Shared.CurrencyCode) and
ListCreditTransactionsParamsFilter.currency (Currencies.CurrencyCode)—are
intentionally different; if they should match, change those types to the
intended wrapper or code enum accordingly (refer to
ListCreditGrantsParamsFilter, GetCreditBalanceParamsFilter,
ListCreditTransactionsParamsFilter), then run make gen-api to regenerate the
OpenAPI spec and SDKs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e25d3f02-532b-44aa-a4c3-45664229ee9b

📥 Commits

Reviewing files that changed from the base of the PR and between fc48236 and b84002e.

⛔ Files ignored due to path filters (1)
  • api/v3/openapi.yaml is excluded by !**/openapi.yaml
📒 Files selected for processing (2)
  • api/spec/packages/aip/src/customers/credits/operations.tsp
  • api/v3/api.gen.go

@GAlexIHU GAlexIHU mentioned this pull request May 20, 2026
@GAlexIHU
GAlexIHU merged commit 9700167 into main May 20, 2026
30 checks passed
@GAlexIHU
GAlexIHU deleted the feat/breakage-rebased branch May 20, 2026 10:17

This branch was previously deployed

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

Labels

release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants