Repository navigation
refactor: ledger collection - #4343
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (2)
📒 Files selected for processing (27)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (22)
📝 WalkthroughWalkthroughThis PR refactors the ledger's transaction template identification system from legacy template names to stable template codes while introducing FBO customer fund source collection with credit-priority-based selection. All affected resolution, correction, annotation, and routing flows are updated to use the new code-based identification, with comprehensive test coverage for both forward and legacy-fallback paths. ChangesLedger Template Code Migration & FBO Collection
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (9)
openmeter/ledger/annotations_test.go (1)
9-17: ⚡ Quick winPlease add the missing-code case here too.
This only locks down the happy path. The fallback to legacy template names is safe only if
TransactionTemplateCodeFromAnnotationsreturns an error whenledger.transaction.template_codeis absent, so a tiny negative-path test next to this one would be really useful.As per coding guidelines, "
**/*_test.go: Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/ledger/annotations_test.go` around lines 9 - 17, Add a negative-path unit test that verifies TransactionTemplateCodeFromAnnotations returns an error when the ledger.transaction.template_code key is absent: create annotations using TransactionAnnotations (or a bare map) without the "ledger.transaction.template_code" entry, call TransactionTemplateCodeFromAnnotations(annotations), and assert that err is non-nil and the returned code is empty (e.g., use require.Error/require.NotNil and require.Empty). Name the test distinctly (e.g., TestTransactionTemplateCodeAnnotations_MissingCode) and keep it parallel-safe like the existing test.AGENTS.md (1)
131-131: ⚡ Quick winMake this guidance a bit more durable and runnable as-is.
"new"/"the user calls out"will age badly in AGENTS, and the barego test -tags=dynamic ./test/creditsexample is easy to run in a way that skips DB-backed coverage despite the note on Line 129. I’d tighten the wording and make the minimum command copy-paste safe.Suggested wording
-When touching ledger, customer credit balance, ledger credit flows, or related API behavior, do not stop at the directly changed package tests. Also run the new credit package tests and the relevant e2e coverage the user calls out, because ledger-only/package-only runs can miss regressions in the older credit stack. At minimum for credit-impacting changes, include `go test -tags=dynamic ./test/credits`. +When touching ledger, customer credit balance, ledger credit flows, or related API behavior, do not stop at the directly changed package tests. Also run the credit test suite and the relevant e2e coverage for the affected flows, because ledger-only/package-only runs can miss regressions in the older credit stack. At minimum for credit-impacting changes, include `env POSTGRES_HOST=127.0.0.1 go test -tags=dynamic ./test/credits`.As per coding guidelines, "Treat AGENTS.md as long-lived project guidance for all agents and contributors; prefer durable wording over time-based wording and keep entries actionable and specific".
🤖 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 `@AGENTS.md` at line 131, Replace the vague, time-sensitive wording ("new", "the user calls out") with durable guidance that explicitly says to run the credit-package tests and any referenced end-to-end coverage whenever making credit-impacting changes, and replace the fragile example command with a copy-paste-safe invocation that forces DB-backed execution; specifically, update the sentence to read something like: "For credit-impacting changes, also run the credit package tests and the referenced e2e coverage; at minimum run: RUN_DB_TESTS=1 go test -tags=dynamic -count=1 ./test/credits" so contributors know to enable DB-backed tests and avoid accidental skips.openmeter/ledger/transactions/codes.go (2)
70-77: ⚡ Quick win
TemplateCodepanicking on unknown templates is a sharp edge.⚠️
templateCode()already returns a useful error;TemplateCode()then converts that to apanic. Callers across the PR use the panicking variant in non-test paths (e.g.,templateCorrectionNotImplemented(TemplateCode(t)), reissue annotation incorrect.go). If a newTransactionTemplatetype is ever added without updating the type switch here, a single missed branch becomes a runtime panic on a correction flow instead of a clean error returned to the caller.Two reasonable options:
- Have
TemplateCodereturn(string, error)and propagate at every call site.- Keep the convenience signature but only use it in places where we already proved the template is one of the known set (e.g., immediately after a successful
templateCodecall).Not a blocker since the switch covers every template type today — flagging because the panic surface widens with every future template addition.
🤖 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/codes.go` around lines 70 - 77, TemplateCode currently panics on unknown templates by calling templateCode and panicking on error; change this to return (string, error) instead of panicking so callers can handle errors safely: update TemplateCode signature to TemplateCode(template TransactionTemplate) (string, error) and simply return templateCode(template) (propagating the error), then update all call sites such as templateCorrectionNotImplemented(TemplateCode(t)) and uses in correct.go to handle the error (propagate or convert to a contextual error) rather than relying on a panic; this preserves the convenience while removing the sharp runtime failure and keeps templateCode as the single source of truth for unknown-template errors.
22-22: ⚡ Quick winConsider renaming
ConvertCurrencyTemplatetoConvertCurrencyFBOTemplatefor consistency.Your gut is right—this operation is genuinely FBO-scoped. The implementation exclusively touches
customerAccounts.FBOAccountand uses FBO-specific credit priority logic. The naming inconsistency stands out though: the other FBO templates (TransferCustomerFBOToAccruedTemplateandTransferCustomerFBOAdvanceToAccruedTemplate) both include "FBO" in their type names, while the const path already signals FBO with"customer.fbo.currency.convert". Since the operation can't logically expand beyond FBO accounts, matching the naming convention now avoids a painful refactor later if the codebase evolves.🤖 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/codes.go` at line 22, Rename the FBO-scoped currency conversion template to match the existing FBO naming convention: change the type/name ConvertCurrencyTemplate to ConvertCurrencyFBOTemplate and update any references to it (including the template constant TemplateCodeConvertCurrency if it references the old name) so the identifier reflects FBO scope; ensure all usages, imports, tests and registration entries that reference ConvertCurrencyTemplate are updated to ConvertCurrencyFBOTemplate to avoid compile errors.openmeter/ledger/collector/correct.go (1)
473-505: 💤 Low valueNice fallback shape — one note on lost priority in the receivable/accrued path.
When the group has no
CustomerFBOentry with a known cost basis (fully backfilled purchase), the fallback returns anilcredit priority because receivable/accrued routes don't carry it. That's an intentional consequence of how routes are dimensioned, but it means the re-issued receivable will land at the default priority bucket rather than the original FBO bucket. If lineage carries the original priority anywhere (e.g., on the realization or its backing metadata), threading it through here would let the re-issue land on the original priority every time. If not, today's behavior is the best you can do with what's in the group — happy to leave as-is.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/ledger/collector/correct.go` around lines 473 - 505, The fallback path in accrualCorrector.backfilledCreditReissueRoute currently returns nil for credit priority when no CustomerFBO route with CostBasis is found, causing re-issued receivables to land in the default priority; update backfilledCreditReissueRoute to attempt to extract and return the original credit priority from the group's lineage/metadata before falling back (e.g., inspect the TransactionGroup, its Transactions/Entries, or any realization/backing metadata fields associated with group.ID() or entries for a stored original priority) and, if found, return that priority along with fallbackCurrency and fallbackCostBasis; only return nil priority if no original priority can be located.openmeter/ledger/collector/collection_fbo.go (3)
127-153: ⚡ Quick win
selectFBOPostingAmountssilently under-allocates when sources are short.If the sum of
source.availableacross all eligible sources is less thantarget, the function returns whatever it could allocate (possibly empty) without signaling that the target wasn't met. That's likely the intended behavior given the comment on the collector side ("returns no transactions when no sources exist"), but it's worth a quick sanity check that the caller incollect.gohandleslen(returned) == 0(or partial coverage) deliberately rather than treating partial output as a full collection. A short doc comment on this function describing the contract would go a long way.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/ledger/collector/collection_fbo.go` around lines 127 - 153, Add a concise doc comment above selectFBOPostingAmounts explaining its contract: it greedily consumes up to target from the provided sources and returns a slice of transactions.PostingAmount that may be empty or represent a partial allocation when the sum of source.available is less than target, and it does not return an error or automatically signal shortfall; callers (e.g., the collector code in collect.go that invokes selectFBOPostingAmounts) must explicitly check the returned slice (or total allocated amount) to detect zero or partial coverage and handle those cases. Ensure the comment names the parameters (sources, target) and the return semantics so future readers and callers know to validate len(returned) or the allocated sum.
28-30: 💤 Low valueThe
accountIdentifierpeek-via-assertion feels a bit indirect. 🧐Type-asserting
customerAccounts.FBOAccountinto a localaccountIdentifierinterface to fish out the namespaced ID is workable, but it's the kind of thing that silently breaks if the concrete account type ever stops exposingID()(or someone wraps it). Two lighter options if you'd like:
- Add
ID() models.NamespacedIDdirectly to theCustomerFBOAccountinterface so the type assertion goes away.- Have
AccountService.GetCustomerAccountsreturn the namespaced ID alongside the account, so this layer doesn't need to introspect.Totally optional — current code works and the failure mode is a clear error string.
Also applies to: 74-77
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/ledger/collector/collection_fbo.go` around lines 28 - 30, The code uses a local interface accountIdentifier plus a type assertion to extract ID() from customerAccounts.FBOAccount which is brittle; instead add ID() models.NamespacedID to the CustomerFBOAccount interface (removing accountIdentifier and assertions) or change AccountService.GetCustomerAccounts to return the NamespacedID alongside the account so the collector code no longer introspects the concrete type; update references in collection_fbo.go where accountIdentifier is used (and the assertion at lines matching the previous use, e.g., the block around handling FBOAccount and lines ~74-77) to consume the ID directly from CustomerFBOAccount or the returned tuple from GetCustomerAccounts.
79-108: ⚖️ Poor tradeoffN+1 balance queries in the FBO collection loop.
listCustomerFBOSourcesiterates over each sub-account and callsBalanceQuerier.GetSubAccountBalanceonce per item. Since theBalanceQuerierinterface only exposes single-item methods (no bulk variant), this scales linearly with the number of customer FBO sub-accounts on the accrual path.For typical customers with a handful of sub-accounts, this is fine. But for multi-cost-basis × multi-priority splits, it's worth considering—parallelizing with
errgroupand a bounded worker pool could cut latency without refactoring the interface. Flagging it for context rather than mandating a fix; not worth doing if customers rarely hit many sub-accounts in practice.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openmeter/ledger/collector/collection_fbo.go` around lines 79 - 108, listCustomerFBOSources currently queries each sub-account balance sequentially (via settledSubAccountBalance -> BalanceQuerier.GetSubAccountBalance), causing N+1 latency; change it to run those balance fetches concurrently with a bounded worker pool using golang.org/x/sync/errgroup: create an errgroup.WithContext(ctx) and a semaphore channel (e.g., make(chan struct{}, maxConcurrency)), pre-allocate a results slice or map keyed by index, iterate subAccounts and for each acquire the semaphore, spawn a goroutine that calls settledSubAccountBalance(ctx, subAccount) and on success stores the fboCollectionSource into the corresponding slot, then release the semaphore; wait for group.Wait(), handle/return the first error, and finally compact the results into the returned slice; keep function names listCustomerFBOSources and settledSubAccountBalance and calls to BalanceQuerier.GetSubAccountBalance unchanged except wrapped in the goroutines, and ensure you use the group's context for cancellability.openmeter/ledger/transactions/correction.go (1)
83-99: 💤 Low valueLovely: code-first, legacy-fallback dispatch reads cleanly. ✨
Small nit on semantics: presence-check then call-by-code means an annotation with a present-but-invalid
template_code(wrong type, empty string) will surface an error rather than fall back to legacy. That's the right call IMO — silent fallback on a malformed new annotation would be much harder to debug — but worth being explicit about that intent in a comment so a future maintainer doesn't "fix" it.🤖 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/correction.go` around lines 83 - 99, Add a clarifying comment to transactionTemplateFromAnnotations explaining that the function intentionally treats a present but invalid ledger.AnnotationTransactionTemplateCode as an error (returned by ledger.TransactionTemplateCodeFromAnnotations) rather than falling back to legacy name lookup; mention that this is deliberate to avoid silently ignoring malformed new-style annotations and reference the decision points (the presence check on ledger.AnnotationTransactionTemplateCode, the call to ledger.TransactionTemplateCodeFromAnnotations, and the fallback to transactionTemplateByLegacyName via transactionTemplateNameFromAnnotations) so future maintainers understand why we error instead of fallback.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@AGENTS.md`:
- Line 131: Replace the vague, time-sensitive wording ("new", "the user calls
out") with durable guidance that explicitly says to run the credit-package tests
and any referenced end-to-end coverage whenever making credit-impacting changes,
and replace the fragile example command with a copy-paste-safe invocation that
forces DB-backed execution; specifically, update the sentence to read something
like: "For credit-impacting changes, also run the credit package tests and the
referenced e2e coverage; at minimum run: RUN_DB_TESTS=1 go test -tags=dynamic
-count=1 ./test/credits" so contributors know to enable DB-backed tests and
avoid accidental skips.
In `@openmeter/ledger/annotations_test.go`:
- Around line 9-17: Add a negative-path unit test that verifies
TransactionTemplateCodeFromAnnotations returns an error when the
ledger.transaction.template_code key is absent: create annotations using
TransactionAnnotations (or a bare map) without the
"ledger.transaction.template_code" entry, call
TransactionTemplateCodeFromAnnotations(annotations), and assert that err is
non-nil and the returned code is empty (e.g., use require.Error/require.NotNil
and require.Empty). Name the test distinctly (e.g.,
TestTransactionTemplateCodeAnnotations_MissingCode) and keep it parallel-safe
like the existing test.
In `@openmeter/ledger/collector/collection_fbo.go`:
- Around line 127-153: Add a concise doc comment above selectFBOPostingAmounts
explaining its contract: it greedily consumes up to target from the provided
sources and returns a slice of transactions.PostingAmount that may be empty or
represent a partial allocation when the sum of source.available is less than
target, and it does not return an error or automatically signal shortfall;
callers (e.g., the collector code in collect.go that invokes
selectFBOPostingAmounts) must explicitly check the returned slice (or total
allocated amount) to detect zero or partial coverage and handle those cases.
Ensure the comment names the parameters (sources, target) and the return
semantics so future readers and callers know to validate len(returned) or the
allocated sum.
- Around line 28-30: The code uses a local interface accountIdentifier plus a
type assertion to extract ID() from customerAccounts.FBOAccount which is
brittle; instead add ID() models.NamespacedID to the CustomerFBOAccount
interface (removing accountIdentifier and assertions) or change
AccountService.GetCustomerAccounts to return the NamespacedID alongside the
account so the collector code no longer introspects the concrete type; update
references in collection_fbo.go where accountIdentifier is used (and the
assertion at lines matching the previous use, e.g., the block around handling
FBOAccount and lines ~74-77) to consume the ID directly from CustomerFBOAccount
or the returned tuple from GetCustomerAccounts.
- Around line 79-108: listCustomerFBOSources currently queries each sub-account
balance sequentially (via settledSubAccountBalance ->
BalanceQuerier.GetSubAccountBalance), causing N+1 latency; change it to run
those balance fetches concurrently with a bounded worker pool using
golang.org/x/sync/errgroup: create an errgroup.WithContext(ctx) and a semaphore
channel (e.g., make(chan struct{}, maxConcurrency)), pre-allocate a results
slice or map keyed by index, iterate subAccounts and for each acquire the
semaphore, spawn a goroutine that calls settledSubAccountBalance(ctx,
subAccount) and on success stores the fboCollectionSource into the corresponding
slot, then release the semaphore; wait for group.Wait(), handle/return the first
error, and finally compact the results into the returned slice; keep function
names listCustomerFBOSources and settledSubAccountBalance and calls to
BalanceQuerier.GetSubAccountBalance unchanged except wrapped in the goroutines,
and ensure you use the group's context for cancellability.
In `@openmeter/ledger/collector/correct.go`:
- Around line 473-505: The fallback path in
accrualCorrector.backfilledCreditReissueRoute currently returns nil for credit
priority when no CustomerFBO route with CostBasis is found, causing re-issued
receivables to land in the default priority; update backfilledCreditReissueRoute
to attempt to extract and return the original credit priority from the group's
lineage/metadata before falling back (e.g., inspect the TransactionGroup, its
Transactions/Entries, or any realization/backing metadata fields associated with
group.ID() or entries for a stored original priority) and, if found, return that
priority along with fallbackCurrency and fallbackCostBasis; only return nil
priority if no original priority can be located.
In `@openmeter/ledger/transactions/codes.go`:
- Around line 70-77: TemplateCode currently panics on unknown templates by
calling templateCode and panicking on error; change this to return (string,
error) instead of panicking so callers can handle errors safely: update
TemplateCode signature to TemplateCode(template TransactionTemplate) (string,
error) and simply return templateCode(template) (propagating the error), then
update all call sites such as templateCorrectionNotImplemented(TemplateCode(t))
and uses in correct.go to handle the error (propagate or convert to a contextual
error) rather than relying on a panic; this preserves the convenience while
removing the sharp runtime failure and keeps templateCode as the single source
of truth for unknown-template errors.
- Line 22: Rename the FBO-scoped currency conversion template to match the
existing FBO naming convention: change the type/name ConvertCurrencyTemplate to
ConvertCurrencyFBOTemplate and update any references to it (including the
template constant TemplateCodeConvertCurrency if it references the old name) so
the identifier reflects FBO scope; ensure all usages, imports, tests and
registration entries that reference ConvertCurrencyTemplate are updated to
ConvertCurrencyFBOTemplate to avoid compile errors.
In `@openmeter/ledger/transactions/correction.go`:
- Around line 83-99: Add a clarifying comment to
transactionTemplateFromAnnotations explaining that the function intentionally
treats a present but invalid ledger.AnnotationTransactionTemplateCode as an
error (returned by ledger.TransactionTemplateCodeFromAnnotations) rather than
falling back to legacy name lookup; mention that this is deliberate to avoid
silently ignoring malformed new-style annotations and reference the decision
points (the presence check on ledger.AnnotationTransactionTemplateCode, the call
to ledger.TransactionTemplateCodeFromAnnotations, and the fallback to
transactionTemplateByLegacyName via transactionTemplateNameFromAnnotations) so
future maintainers understand why we error instead of fallback.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: b48c2d3c-3a79-4e2b-9892-26cb5ab984f9
⛔ Files ignored due to path filters (1)
tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (25)
AGENTS.mdopenmeter/ledger/annotations.goopenmeter/ledger/annotations_test.goopenmeter/ledger/chargeadapter/creditpurchase_test.goopenmeter/ledger/collector/collect.goopenmeter/ledger/collector/collection_fbo.goopenmeter/ledger/collector/collection_fbo_test.goopenmeter/ledger/collector/correct.goopenmeter/ledger/routingrules/routingrules.goopenmeter/ledger/routingrules/routingrules_test.goopenmeter/ledger/transactions/accrual.goopenmeter/ledger/transactions/accrual_test.goopenmeter/ledger/transactions/codes.goopenmeter/ledger/transactions/collection.goopenmeter/ledger/transactions/correction.goopenmeter/ledger/transactions/correction_test.goopenmeter/ledger/transactions/customer.goopenmeter/ledger/transactions/earnings_test.goopenmeter/ledger/transactions/fx.goopenmeter/ledger/transactions/legacy.goopenmeter/ledger/transactions/resolve.goopenmeter/ledger/transactions/resolve_test.gopkg/cmpx/compare.gotools/migrate/migrations/20260511134625_ledger_transaction_template_codes.down.sqltools/migrate/migrations/20260511134625_ledger_transaction_template_codes.up.sql
06531e9 to
70fd800
Compare
70fd800 to
c87fdc8
Compare
c87fdc8 to
5f21bff
Compare
Summary
Refactor ledger customer FBO collection and transaction template annotations in preparation for credit expiration/breakage work.
Collection
transactionsand intocollector.TransferCustomerFBOToAccruedTemplateto receive concretePostingAmountsources instead of resolving/sorting balances internally.credit_priority, then sub-account cursor.cmpx.Comparablehelper for reusable sortable domain values.Template annotations
customer.fbo.collect.ledger.transaction.template_nametoledger.transaction.template_codefor active templates.Correction / routing cleanup
Tests
Testing