Skip to content

refactor: ledger collection - #4343

Merged
GAlexIHU merged 3 commits into
mainfrom
refactor/ledger-collector
May 13, 2026
Merged

GAlexIHU merged 3 commits into
mainfrom
refactor/ledger-collector

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Refactor ledger customer FBO collection and transaction template annotations in preparation for credit expiration/breakage work.

Collection

  • Move customer FBO source selection out of transactions and into collector.
  • Change TransferCustomerFBOToAccruedTemplate to receive concrete PostingAmount sources instead of resolving/sorting balances internally.
  • Keep template responsibility focused on posting shape, validation, and route-preserving FBO -> accrued entries.
  • Add deterministic FBO collection ordering in collector by credit_priority, then sub-account cursor.
  • Add small cmpx.Comparable helper for reusable sortable domain values.

Template annotations

  • Replace persisted Go type-name template annotations with canonical dotted template codes, e.g. customer.fbo.collect.
  • Add migration from ledger.transaction.template_name to ledger.transaction.template_code for active templates.
  • Keep archived receivable payment templates legacy-only; they are not recreated and old rows remain dispatchable by legacy name.
  • Split correction dispatch into separate code and legacy-name paths.

Correction / routing cleanup

  • Update collector correction flows to use template codes.
  • Preserve credit priority when reissuing backfilled credit during correction.
  • Allow FBO cost-basis translation validation in both directions, with priority consistency checks.

Tests

  • Add coverage for collector-owned FBO source selection/order.
  • Add coverage for canonical template annotations and legacy correction dispatch.
  • Add routing rule tests for FBO cost-basis translation.
  • Add credit-purchase assertions for emitted template codes.

Testing

nix develop --impure .#ci -c env POSTGRES_HOST=127.0.0.1 go test -tags=dynamic ./openmeter/ledger/transactions ./test/credits
nix develop --impure .#ci -c make lint-go


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

# Release Notes

* **New Features**
  * Introduced FBO (Flexible Balance Organization) credit allocation with priority-based source selection for improved credit management.

* **Refactor**
  * Transitioned transaction system from template names to stable template codes for improved consistency and maintainability.
  * Refactored transaction annotation and resolution logic across collector and correction workflows.

* **Tests**
  * Added comprehensive test coverage for FBO source selection, priority ordering, and tie-breaking behavior.
  * Updated existing transaction tests to align with new template code system.

* **Chores**
  * Added database migration to update transaction annotations from template names to codes.

<!-- review_stack_entry_start -->

[![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/openmeterio/openmeter/pull/4343)

<!-- review_stack_entry_end -->
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

@GAlexIHU GAlexIHU added the release-note/misc Miscellaneous changes label May 11, 2026
@GAlexIHU
GAlexIHU requested a review from a team as a code owner May 11, 2026 17:50
@coderabbitai

coderabbitai Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9ae72542-eadd-4523-b2d2-bee74f92977d

📥 Commits

Reviewing files that changed from the base of the PR and between c87fdc8 and 5f21bff.

⛔ Files ignored due to path filters (2)
  • migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (27)
  • .agents/skills/ledger/SKILL.md
  • openmeter/ledger/annotations.go
  • openmeter/ledger/annotations_test.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
  • openmeter/ledger/collector/collect.go
  • openmeter/ledger/collector/collection_fbo.go
  • openmeter/ledger/collector/collection_fbo_test.go
  • openmeter/ledger/collector/correct.go
  • openmeter/ledger/routingrules/routingrules.go
  • openmeter/ledger/routingrules/routingrules_test.go
  • openmeter/ledger/transactions/accrual.go
  • openmeter/ledger/transactions/accrual_test.go
  • openmeter/ledger/transactions/codes.go
  • openmeter/ledger/transactions/collection.go
  • openmeter/ledger/transactions/correction.go
  • openmeter/ledger/transactions/correction_test.go
  • openmeter/ledger/transactions/customer.go
  • openmeter/ledger/transactions/earnings.go
  • openmeter/ledger/transactions/earnings_test.go
  • openmeter/ledger/transactions/fx.go
  • openmeter/ledger/transactions/legacy.go
  • openmeter/ledger/transactions/resolve.go
  • openmeter/ledger/transactions/resolve_test.go
  • openmeter/ledger/transactions/template.go
  • pkg/cmpx/compare.go
  • tools/migrate/migrations/20260513072457_ledger_transaction_template_codes.down.sql
  • tools/migrate/migrations/20260513072457_ledger_transaction_template_codes.up.sql
✅ Files skipped from review due to trivial changes (1)
  • .agents/skills/ledger/SKILL.md
🚧 Files skipped from review as they are similar to previous changes (22)
  • openmeter/ledger/transactions/template.go
  • openmeter/ledger/transactions/earnings_test.go
  • openmeter/ledger/annotations_test.go
  • openmeter/ledger/transactions/resolve_test.go
  • openmeter/ledger/transactions/fx.go
  • openmeter/ledger/collector/collection_fbo.go
  • pkg/cmpx/compare.go
  • openmeter/ledger/transactions/collection.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
  • openmeter/ledger/collector/collect.go
  • openmeter/ledger/transactions/resolve.go
  • openmeter/ledger/transactions/accrual_test.go
  • openmeter/ledger/routingrules/routingrules.go
  • openmeter/ledger/transactions/codes.go
  • openmeter/ledger/routingrules/routingrules_test.go
  • openmeter/ledger/transactions/legacy.go
  • openmeter/ledger/transactions/correction_test.go
  • openmeter/ledger/collector/correct.go
  • openmeter/ledger/transactions/correction.go
  • openmeter/ledger/collector/collection_fbo_test.go
  • openmeter/ledger/transactions/customer.go
  • openmeter/ledger/transactions/accrual.go

📝 Walkthrough

Walkthrough

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

Changes

Ledger Template Code Migration & FBO Collection

Layer / File(s) Summary
Interface Contracts & Type Definitions
openmeter/ledger/transactions/template.go, openmeter/ledger/transactions/collection.go, pkg/cmpx/compare.go
TransactionTemplate interface requires a new code() TransactionTemplateCode method. Exports PostingAmount struct bundling posting address and amount. Introduces Comparable[T] interface for deterministic ordering.
Template Code Mapping & Lookup
openmeter/ledger/transactions/codes.go
Centralizes TransactionTemplateCode type and stable code constants for all template variants. Implements code-to-template and legacy-name-to-code lookup maps. Provides TemplateCode() wrapper and annotateTemplateTransaction() helpers.
Annotation API Migration from Names to Codes
openmeter/ledger/annotations.go, openmeter/ledger/annotations_test.go
Exports AnnotationTransactionTemplateCode constant; removes AnnotationTransactionTemplateName. Updates TransactionAnnotations() to accept templateCode instead of templateName. Adds TransactionTemplateCodeFromAnnotations() helper to extract and validate codes.
Collection & Comparable Types
openmeter/ledger/transactions/collection.go
Removes internal prioritized-FBO logic. Exports PostingAmount struct for explicit source allocation.
FBO Source Collection Implementation
openmeter/ledger/collector/collection_fbo.go
Implements collectCustomerFBO() with fboCollectionSource ordering by credit priority and cursor. Adds listCustomerFBOSources() to enumerate sub-accounts and query settled balances. Implements selectFBOPostingAmounts() to allocate amounts up to target.
FBO Collection Tests
openmeter/ledger/collector/collection_fbo_test.go
Tests FBO source ordering by credit priority and deterministic tie-breaking by SubAccountID. Provides test helpers (newTestAccrualCollector, fundPriority, fundPriorityWithCostBasis) for FBO sub-account setup.
TransferCustomerFBOToAccrued Refactor
openmeter/ledger/transactions/accrual.go
Changes TransferCustomerFBOToAccruedTemplate from single Amount to Sources []PostingAmount. Updates Validate() to check each source address/amount and resolve() to build entries per source with route-preserving grouping. Adds code() method.
TransferCustomerFBOToAccrued Tests
openmeter/ledger/transactions/accrual_test.go
Updates accrual tests to use Sources list; verifies priority consumption, cost-basis preservation, and correction behavior with multi-source inputs.
Template code() Method Implementations
openmeter/ledger/transactions/{customer,accrual,earnings,fx,legacy}.go
Adds code() implementations returning corresponding TemplateCode constants for all templates. Updates correction error reporting to use TemplateCode() instead of legacy template names.
Transaction Resolution & Template Annotation
openmeter/ledger/transactions/resolve.go, openmeter/ledger/transactions/resolve_test.go
Updates ResolveTransactions() to use appendResolvedTemplateTransaction(). Removes reflect-based TemplateName() helpers. Test directly calls annotateTemplateTransaction() and verifies template-code and direction annotations.
Correction Template Dispatch & Resolution
openmeter/ledger/transactions/correction.go, openmeter/ledger/transactions/correction_test.go
Updates CorrectTransaction() to use transactionTemplateFromAnnotations() preferring template-code annotation with fallback to legacy template-name. Handles annotateTemplateTransaction() as fallible. Adds comprehensive tests for both code and legacy-name paths.
Collector & Credit Realization with FBO
openmeter/ledger/collector/collect.go
Updates resolveCollectedInputs() to validate inputs and call collectCustomerFBO() for sources. Passes sources to transfer template instead of single amount. Updates creditRealizationAnnotationsForCollectedInput() to use template-code-based annotation lookup.
Correction Accrual & Backfilled Credit Reissue
openmeter/ledger/collector/correct.go
Updates planRecognizedEarningsSegment() and planBackfilledAdvanceSegment() to forward by template code. Introduces backfilledCreditReissueRoute() preferring CustomerFBO routes with priority. Annotates reissued templates using TemplateCode().
Routing Rule Bidirectional Validation
openmeter/ledger/routingrules/routingrules.go, openmeter/ledger/routingrules/routingrules_test.go
Updates RequireFBOCostBasisTranslationRule.Validate() to call requireKnownToUnknownCostBasisTranslationEitherDirection(). Adds tests verifying both orderings succeed and mismatched priority fails.
Credit Purchase Adapter Integration Tests
openmeter/ledger/chargeadapter/creditpurchase_test.go
Adds template-code assertions to credit purchase tests using transactionTemplateCodes() helper. Verifies expected template composition for promotional purchases, initiations, and payment settlements.
Earnings Test Template Lookup
openmeter/ledger/transactions/earnings_test.go
Updates findForwardTransaction() helper to match by TemplateCode() and use TransactionTemplateCodeFromAnnotations().
Data Migration & Testing Guidance
tools/migrate/migrations/20260513072457_ledger_transaction_template_codes.{up,down}.sql, .agents/skills/ledger/SKILL.md
SQL migrations replace ledger.transaction.template_name with ledger.transaction.template_code using hardcoded mapping. Updates SKILL.md to document running credit package tests for ledger changes.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

area/billing

Suggested reviewers

  • turip
  • tothandras
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor: ledger collection' is concise and directly reflects the main structural change, though it covers only part of the substantial refactoring work (template codes, migrations, routing rules).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/ledger-collector

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (9)
openmeter/ledger/annotations_test.go (1)

9-17: ⚡ Quick win

Please add the missing-code case here too.

This only locks down the happy path. The fallback to legacy template names is safe only if TransactionTemplateCodeFromAnnotations returns an error when ledger.transaction.template_code is 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 win

Make this guidance a bit more durable and runnable as-is.

"new" / "the user calls out" will age badly in AGENTS, and the bare go test -tags=dynamic ./test/credits example 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

TemplateCode panicking on unknown templates is a sharp edge. ⚠️

templateCode() already returns a useful error; TemplateCode() then converts that to a panic. Callers across the PR use the panicking variant in non-test paths (e.g., templateCorrectionNotImplemented(TemplateCode(t)), reissue annotation in correct.go). If a new TransactionTemplate type 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 TemplateCode return (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 templateCode call).

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 win

Consider renaming ConvertCurrencyTemplate to ConvertCurrencyFBOTemplate for consistency.

Your gut is right—this operation is genuinely FBO-scoped. The implementation exclusively touches customerAccounts.FBOAccount and uses FBO-specific credit priority logic. The naming inconsistency stands out though: the other FBO templates (TransferCustomerFBOToAccruedTemplate and TransferCustomerFBOAdvanceToAccruedTemplate) 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 value

Nice fallback shape — one note on lost priority in the receivable/accrued path.

When the group has no CustomerFBO entry with a known cost basis (fully backfilled purchase), the fallback returns a nil credit 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

selectFBOPostingAmounts silently under-allocates when sources are short.

If the sum of source.available across all eligible sources is less than target, 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 in collect.go handles len(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 value

The accountIdentifier peek-via-assertion feels a bit indirect. 🧐

Type-asserting customerAccounts.FBOAccount into a local accountIdentifier interface 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 exposing ID() (or someone wraps it). Two lighter options if you'd like:

  1. Add ID() models.NamespacedID directly to the CustomerFBOAccount interface so the type assertion goes away.
  2. Have AccountService.GetCustomerAccounts return 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 tradeoff

N+1 balance queries in the FBO collection loop.

listCustomerFBOSources iterates over each sub-account and calls BalanceQuerier.GetSubAccountBalance once per item. Since the BalanceQuerier interface 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 errgroup and 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 value

Lovely: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4fed364 and 06531e9.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (25)
  • AGENTS.md
  • openmeter/ledger/annotations.go
  • openmeter/ledger/annotations_test.go
  • openmeter/ledger/chargeadapter/creditpurchase_test.go
  • openmeter/ledger/collector/collect.go
  • openmeter/ledger/collector/collection_fbo.go
  • openmeter/ledger/collector/collection_fbo_test.go
  • openmeter/ledger/collector/correct.go
  • openmeter/ledger/routingrules/routingrules.go
  • openmeter/ledger/routingrules/routingrules_test.go
  • openmeter/ledger/transactions/accrual.go
  • openmeter/ledger/transactions/accrual_test.go
  • openmeter/ledger/transactions/codes.go
  • openmeter/ledger/transactions/collection.go
  • openmeter/ledger/transactions/correction.go
  • openmeter/ledger/transactions/correction_test.go
  • openmeter/ledger/transactions/customer.go
  • openmeter/ledger/transactions/earnings_test.go
  • openmeter/ledger/transactions/fx.go
  • openmeter/ledger/transactions/legacy.go
  • openmeter/ledger/transactions/resolve.go
  • openmeter/ledger/transactions/resolve_test.go
  • pkg/cmpx/compare.go
  • tools/migrate/migrations/20260511134625_ledger_transaction_template_codes.down.sql
  • tools/migrate/migrations/20260511134625_ledger_transaction_template_codes.up.sql

@turip turip left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

overal looks good

Comment thread openmeter/ledger/transactions/codes.go Resolved
Comment thread AGENTS.md Resolved
turip
turip previously approved these changes May 11, 2026
@GAlexIHU
GAlexIHU force-pushed the refactor/ledger-collector branch from 70fd800 to c87fdc8 Compare May 11, 2026 19:47
@GAlexIHU
GAlexIHU requested a review from turip May 11, 2026 19:47
@GAlexIHU
GAlexIHU enabled auto-merge (squash) May 11, 2026 19:48
turip
turip previously approved these changes May 13, 2026

@turip turip left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGFM, rebased to latest main.

@GAlexIHU
GAlexIHU merged commit 968f4d1 into main May 13, 2026
25 checks passed
@GAlexIHU
GAlexIHU deleted the refactor/ledger-collector branch May 13, 2026 07:36
This was referenced May 17, 2026

This branch was previously deployed

1 inactive deployment
dev — 5f21bff3 Deployed May 13, 2026 by turip via Migration Checks #14342
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants