Repository navigation
feat!: breakage - #4395
feat!: breakage#4395
Conversation
…nt in transaction
📝 WalkthroughWalkthroughImplements credit expiration (breakage) and point-in-time (as-of) balance/transaction support across API, ledger, collector, storage, wiring, migrations, docs, and tests. ChangesCredit Expiration + As-Of Querying
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Suggested reviewers
✨ Finishing Touches🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
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 winScope the credit-movement subquery to the request namespace.
Right now the
IN (...)subquery aggregates FBO movement across every namespace, and the outerledgertransactiondb.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 valueNice 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:
parseTextUnmarshalerPtrexplicitly 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 valueUse plain
@queryfor the scalar DateTime parameter.The
deepObjectstyle is for object types (e.g.,filter[currency][eq]=USD). DateTime is a scalar, so it should use plain@querylike 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-apiafter 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 valueMinor 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: "-
planmeans... -releasemeans... -reopenmeans... -breakage impactmeans..."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 winClarify 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 winAlign
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 otherValidate()methods inopenmeter/**.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() errormethods, collect all validation issues intovar errs []errorand returnmodels.NewNillableGenericValidationError(errors.Join(errs...))instead of returning on the first invalid field”.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/ledger/breakage/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 winUse 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.Decimalequality in tests, preferrequire.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 winUse 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: Uset.Context()in tests when atesting.Tortesting.TBis available instead of introducingcontext.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 winDrop the redundant unique index on
id.
idis 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 winUse
clock.SetTime(...)for later time jumps after the initial freeze.After the first
FreezeTime+defer pair, these additional freezes can be replaced withSetTimeto keep the freeze lifecycle simple and aligned with the guideline.As per coding guidelines:
**/*_test.go: When usingclock.FreezeTime(...)in tests, immediately pair it withdefer 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 winPrefer float-based
require.Equalforalpacadecimalassertions 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 assertingalpacadecimal.Decimalequality in tests, preferrequire.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 winPlease align these decimal assertions with the project’s test convention.
For these new checks, prefer
require.Equal(t, expectedFloat64, actual.InexactFloat64())instead ofrequire.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 winUse the repo’s preferred decimal assertion style here.
Please switch this to
require.Equal(t, expectedFloat64, actual.InexactFloat64())instead ofrequire.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 valueConsider whether
ForUpdate()is intentionally omitted here.Unlike
ListReleaseRecordsandListCandidateRecords, this query doesn't useForUpdate(). 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
⛔ Files ignored due to path filters (31)
api/v3/openapi.yamlis excluded by!**/openapi.yamlopenmeter/ent/db/chargecreditpurchase.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase/chargecreditpurchase.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase_update.gois excluded by!**/ent/db/**openmeter/ent/db/client.gois excluded by!**/ent/db/**openmeter/ent/db/cursor.gois excluded by!**/ent/db/**openmeter/ent/db/ent.gois excluded by!**/ent/db/**openmeter/ent/db/entmixinaccessor.gois excluded by!**/ent/db/**openmeter/ent/db/expose.gois excluded by!**/ent/db/**openmeter/ent/db/hook/hook.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord/ledgerbreakagerecord.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord/where.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_create.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_delete.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_query.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerbreakagerecord_update.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry/ledgerentry.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry/where.gois excluded by!**/ent/db/**openmeter/ent/db/ledgerentry_create.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**openmeter/ent/db/paginate.gois excluded by!**/ent/db/**openmeter/ent/db/predicate/predicate.gois excluded by!**/ent/db/**openmeter/ent/db/runtime.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**openmeter/ent/db/tx.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (99)
api/spec/packages/aip/src/customers/credits/grant.tspapi/spec/packages/aip/src/customers/credits/ledger.tspapi/spec/packages/aip/src/customers/credits/operations.tspapi/v3/api.gen.goapi/v3/filters/parse.goapi/v3/filters/parse_test.goapi/v3/handlers/customers/credits/convert.goapi/v3/handlers/customers/credits/get_balance.goapi/v3/handlers/customers/credits/list_transactions_test.goapp/common/billing.goapp/common/charges.goapp/common/customerbalance.gocmd/billing-worker/wire_gen.gocmd/jobs/internal/wire_gen.gocmd/server/wire_gen.goe2e/customer_credits_v3_test.goopenmeter/billing/charges/creditpurchase/adapter/charge.goopenmeter/billing/charges/creditpurchase/adapter/funded_credit_activity.goopenmeter/billing/charges/creditpurchase/adapter/funded_credit_activity_test.goopenmeter/billing/charges/creditpurchase/adapter/mapper.goopenmeter/billing/charges/creditpurchase/charge.goopenmeter/billing/charges/creditpurchase/funded_credit_activity.goopenmeter/billing/charges/creditpurchase/service/promotional.goopenmeter/billing/creditgrant/service.goopenmeter/billing/creditgrant/service/service.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.goopenmeter/ent/schema/chargescreditpurchase.goopenmeter/ent/schema/ledger_breakage_record.goopenmeter/ent/schema/ledger_entry.goopenmeter/ledger/account.goopenmeter/ledger/account/account.goopenmeter/ledger/annotations.goopenmeter/ledger/balance.goopenmeter/ledger/breakage/README.mdopenmeter/ledger/breakage/adapter/adapter.goopenmeter/ledger/breakage/adapter/record.goopenmeter/ledger/breakage/breakage_impacts.goopenmeter/ledger/breakage/noop.goopenmeter/ledger/breakage/service.goopenmeter/ledger/breakage/types.goopenmeter/ledger/chargeadapter/creditpurchase.goopenmeter/ledger/chargeadapter/creditpurchase_test.goopenmeter/ledger/chargeadapter/flatfee.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/helpers.goopenmeter/ledger/chargeadapter/usagebased.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/collector/README.mdopenmeter/ledger/collector/collect.goopenmeter/ledger/collector/collection_fbo.goopenmeter/ledger/collector/collection_fbo_test.goopenmeter/ledger/collector/correct.goopenmeter/ledger/collector/service.goopenmeter/ledger/customerbalance/README.mdopenmeter/ledger/customerbalance/expired_loader.goopenmeter/ledger/customerbalance/expired_loader_test.goopenmeter/ledger/customerbalance/facade.goopenmeter/ledger/customerbalance/facade_test.goopenmeter/ledger/customerbalance/funded_loader.goopenmeter/ledger/customerbalance/ledger_loader.goopenmeter/ledger/customerbalance/loaders.goopenmeter/ledger/customerbalance/noop.goopenmeter/ledger/customerbalance/service.goopenmeter/ledger/customerbalance/service_test.goopenmeter/ledger/customerbalance/testenv_test.goopenmeter/ledger/customerbalance/transactions.goopenmeter/ledger/customerbalance/transactions_test.goopenmeter/ledger/historical/adapter/ledger.goopenmeter/ledger/historical/adapter/ledger_test.goopenmeter/ledger/historical/adapter/sumentries_query.goopenmeter/ledger/historical/balance.goopenmeter/ledger/historical/entry.goopenmeter/ledger/impact.goopenmeter/ledger/impact_test.goopenmeter/ledger/ledger_test.goopenmeter/ledger/noop/noop.goopenmeter/ledger/primitives.goopenmeter/ledger/query.goopenmeter/ledger/resolvers/account.goopenmeter/ledger/routingrules/defaults.goopenmeter/ledger/routingrules/routingrules.goopenmeter/ledger/routingrules/routingrules_test.goopenmeter/ledger/testutils/integration.goopenmeter/ledger/transactions/accrual.goopenmeter/ledger/transactions/breakage.goopenmeter/ledger/transactions/codes.goopenmeter/ledger/transactions/collection.goopenmeter/ledger/transactions/correction_leg.goopenmeter/ledger/transactions/entry_identity.goopenmeter/ledger/transactions/input.goopenmeter/ledger/transactions/testutils/anytransaction.gotest/app/stripe/invoice_test.gotest/credits/base.gotest/credits/creditgrant_test.gotest/credits/sanity_test.gotools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.down.sqltools/migrate/migrations/20260514084134_add_ledger_entry_identity_key.up.sqltools/migrate/migrations/20260517121831_add_credit_expiration_breakage.down.sqltools/migrate/migrations/20260517121831_add_credit_expiration_breakage.up.sql
| 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...) | ||
| } |
There was a problem hiding this comment.
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.
| 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...) | ||
| } |
There was a problem hiding this comment.
🛠️ 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...).
| switch i.SourceKind { | ||
| case SourceKindUsage, SourceKindUsageCorrection, SourceKindCreditPurchaseCorrection, SourceKindAdvanceBackfill: | ||
| default: | ||
| errs = append(errs, fmt.Errorf("invalid release source kind: %s", i.SourceKind)) | ||
| } |
There was a problem hiding this comment.
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.
| 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 | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
| 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...) | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
| Type: creditTransactionType(fboImpact), | ||
| Currency: currency, | ||
| Amount: fboImpact, |
There was a problem hiding this comment.
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.
| if i.AsOf != nil && i.AsOf.IsZero() { | ||
| return ErrListTransactionsInputInvalid.WithAttrs(models.Attributes{ | ||
| "reason": "as_of_invalid", | ||
| "as_of": i.AsOf, | ||
| }) | ||
| } |
There was a problem hiding this comment.
🛠️ 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).
| 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", | ||
| }) | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
| 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.
| 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 | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
| 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, | ||
| } | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
api/v3/filters/parse_test.goe2e/customer_credits_v3_test.go
| 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) | ||
| }) | ||
| } |
There was a problem hiding this comment.
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.
| 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.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
api/spec/packages/aip/src/customers/credits/operations.tsp (1)
140-140:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winThis aligns with the existing backend implementation—no breaking change
Good catch on this change! The backend already expects
StringFieldFilterExactforGetCreditBalanceParamsFilter.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
timestampparameter looks solid—using plain@queryfor the DateTime is correct, and the filter below correctly usesdeepObjectstyle for complex objects.Remember to run
make gen-apiafter 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
⛔ Files ignored due to path filters (1)
api/v3/openapi.yamlis excluded by!**/openapi.yaml
📒 Files selected for processing (2)
api/spec/packages/aip/src/customers/credits/operations.tspapi/v3/api.gen.go
#4371
Overview
Fixes #(issue)
Notes for reviewer
Summary by CodeRabbit
New Features
Improvements
Tests & Docs