Repository navigation
fix(ledger): preserve source attribution in earnings lineage - #5100
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (11)
Included review availability: Your plan provides up to 8 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthroughEarnings recognition now plans exact accrued sources from lineage allocation metadata. It passes those sources into transaction resolution and updates only the matching lineage segments. Tests cover source isolation, paid backfills, refunds, and deferred promotional credits. ChangesAllocation-aware earnings recognition
Priority: ➖ Normal — Schedule the earnings-lineage fix because recognition now selects allocation-backed sources and keeps ledger postings aligned with lineage transitions across promotional and paid credits. Estimated code review effort: 4 (Complex) | ~45 minutes Merge Risk: ⚪ Minimal · up to The recognition changes preserve allocation lineage across journal postings and segment transitions, with regression coverage for the affected scenarios. No merge-blocking risk is identified. Sequence Diagram(s)sequenceDiagram
participant RecognizeEarnings
participant planRecognition
participant LineageService
participant recognitionGroup
RecognizeEarnings->>planRecognition: request customer recognition plan
planRecognition->>LineageService: load customer lineages
planRecognition->>recognitionGroup: load original or backfilled groups
recognitionGroup-->>planRecognition: return accrued source entries
planRecognition-->>RecognizeEarnings: return selected sources and allocations
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✨ 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 |
| if t.Sources != nil { | ||
| total := alpacadecimal.Zero | ||
| for i, source := range t.Sources { | ||
| if source.Address == nil || source.Address.AccountType() != ledger.AccountTypeCustomerAccrued { | ||
| return fmt.Errorf("sources[%d]: customer accrued address is required", i) | ||
| } | ||
| route := source.Address.Route().Route() | ||
| if !route.Currency.Equal(t.Currency) || route.CostBasis == nil || !isCreditBackedAccruedIdentity(source.Identity) { | ||
| return fmt.Errorf("sources[%d]: known-cost credit-backed accrued in the recognition currency is required", i) | ||
| } | ||
| if err := ledger.ValidateTransactionAmount(source.Amount); err != nil { | ||
| return fmt.Errorf("sources[%d]: %w", i, err) | ||
| } | ||
| total = total.Add(source.Amount) | ||
| } | ||
| if !total.Equal(t.Amount) { | ||
| return fmt.Errorf("source total %s does not match recognition amount %s", total, t.Amount) | ||
| } |
There was a problem hiding this comment.
Validation errors return early
The new Sources validation returns a plain fmt.Errorf as soon as it encounters the first invalid source. This violates the repository directive that Validate() methods collect field errors and return them through models.NewNillableGenericValidationError(errors.Join(...)), so the repository requirement must be satisfied before merging.
Context Used: AGENTS.md (source)
Prompt To Fix With AI
This is a comment left during a code review.
Path: openmeter/ledger/transactions/earnings.go
Line: 42-59
Comment:
**Validation errors return early**
The new `Sources` validation returns a plain `fmt.Errorf` as soon as it encounters the first invalid source. This violates the repository directive that `Validate()` methods collect field errors and return them through `models.NewNillableGenericValidationError(errors.Join(...))`, so the repository requirement must be satisfied before merging.
**Context Used:** AGENTS.md ([source](https://github.com/openmeterio/openmeter/blob/main/AGENTS.md))
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
A spend of 2 promotional custom-currency credits plus an 8-credit advance, followed by an 8-credit paid backfill at USD 0.5, left the journal at 8 earnings / 2 deferred accrued while lineage incorrectly marked 2 promotional + 6 paid credits recognized. The real-service regression was reproduced on the base before the fix.
Recognition now selects accrued slices from each lineage's original allocation bucket or recorded backfill group, preserving source, spend, currency, cost basis, and tax route. One selection drives both journal postings and segment transitions, with the original backing retained for correction. This changes forward recognition; it does not repair historical misattributed segments.
Validation:
-tags=dynamic: 8,017 tests, 9 skipped, zero failures. Notification/Svix passed; no exclusion added.--allow-serial-runnersafter process-lock contention.Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Greptile Summary
This PR changes earnings recognition to derive both ledger postings and lineage transitions from the same source-attributed accrued slices.
Confidence Score: 4/5
The recognition behavior appears sound, but the explicit repository validation requirement in
openmeter/ledger/transactions/earnings.gomust be satisfied before merging.Source selection, journal posting, and lineage transition amounts remain aligned, and the investigated attribution and lifecycle paths did not establish a behavioral regression; the remaining finding is the newly added immediate-return validation logic.
Files Needing Attention: openmeter/ledger/transactions/earnings.go
Important Files Changed
Sequence Diagram
sequenceDiagram participant R as Earnings recognizer participant L as Lineage service participant B as Ledger balance query participant G as Original/backfill groups participant J as Ledger journal R->>L: Load eligible lineage segments R->>B: Load accrued buckets by source and spend R->>G: Load each segment's allocation or backfill group G-->>R: Original source, route, and backing R->>R: Intersect segment backing with live accrued buckets R->>J: Commit selected source slices to earnings R->>L: Transition the same selected slices Note over J,L: Journal postings and lineage transitions commit atomicallyPrompt To Fix All With AI
Reviews (1): Last reviewed commit: "fix(ledger): preserve source attribution..." | Re-trigger Greptile
Context used: