Skip to content

fix(ledger): preserve source attribution in earnings lineage - #5100

Merged
GAlexIHU merged 1 commit into
mainfrom
codex/fix-recognition-lineage-attribution
Sep 8, 2026
Merged

GAlexIHU merged 1 commit into
mainfrom
codex/fix-recognition-lineage-attribution

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Full root Go suite in the CI shell, PostgreSQL enabled and -tags=dynamic: 8,017 tests, 9 skipped, zero failures. Notification/Svix passed; no exclusion added.
  • v3 Go SDK build, vet, and tests passed.
  • Root, SDK, and e2e Go lint plus e2e vet passed. The e2e lint step was rerun with --allow-serial-runners after process-lock contention.
  • Regression covers the exact promotional/paid split, 3+5 partial backfills, source/backing identity, refunds, and retries after recognition and correction.
  • Recognizer coverage also checks unrelated accrued sources on the same subaccount and partially available source balances.

Summary by CodeRabbit

  • New Features

    • Earnings recognition now tracks and posts against the exact eligible source allocations.
    • Recognition supports explicitly selected accrued sources with validation for currency, cost basis, funding route, and amount.
    • Backfilled advances are matched to their recorded backing sources, preserving source and allocation details.
  • Bug Fixes

    • Prevented unrelated accrued balances from being recognized.
    • Promotional credits without a known cost basis remain deferred during paid backfill recognition.
  • Documentation

    • Clarified credit-backed earnings recognition behavior and lineage consistency.

Greptile Summary

This PR changes earnings recognition to derive both ledger postings and lineage transitions from the same source-attributed accrued slices.

  • Loads each lineage's original allocation transaction group and allocation sort hint.
  • Selects recognizable accrued value by source, spend, route, and backfill group.
  • Preserves prior segment state and backing references for correction.
  • Adds focused recognizer and end-to-end coverage for promotional credits, paid backfills, partial recognition, retries, and refunds.
  • Introduces one repository validation-convention violation that should be corrected before merging.

Confidence Score: 4/5

The recognition behavior appears sound, but the explicit repository validation requirement in openmeter/ledger/transactions/earnings.go must 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

Filename Overview
openmeter/ledger/recognizer/sources.go Adds source-aware recognition planning that intersects lineage backing with live accrued source/spend buckets.
openmeter/ledger/recognizer/recognize.go Uses one recognition allocation plan for both journal postings and lineage segment transitions.
openmeter/billing/charges/lineage/adapter/lineage.go Hydrates original transaction-group and allocation-sort references for loaded lineages.
openmeter/ledger/transactions/earnings.go Supports caller-selected accrued slices, but the new validation branches violate the repository's aggregated-validation convention.
test/credits/recognition_lineage_test.go Covers source-preserving paid backfill recognition, partial backfills, retries, and correction through the real service lifecycle.

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 atomically
Loading

Fix all with Greploop Fix All in Claude Code Fix All in Codex

Prompt To Fix All With AI
### Issue 1
openmeter/ledger/transactions/earnings.go:42-59
**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.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Reviews (1): Last reviewed commit: "fix(ledger): preserve source attribution..." | Re-trigger Greptile

Greptile also left 1 inline comment on this PR.

Context used:

@GAlexIHU
GAlexIHU requested a review from a team as a code owner September 8, 2026 13:14
@GAlexIHU GAlexIHU added the release-note/bug-fix Release note: Bug Fixes label Sep 8, 2026
@coderabbitai

coderabbitai Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 40425435-a550-4c8a-8fcf-3e0cab69befb

📥 Commits

Reviewing files that changed from the base of the PR and between 223a106 and cce6470.

📒 Files selected for processing (11)
  • openmeter/billing/charges/lineage/adapter/lineage.go
  • openmeter/billing/charges/lineage/service.go
  • openmeter/ledger/README.md
  • openmeter/ledger/chargeadapter/flatfee_test.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
  • openmeter/ledger/recognizer/recognize.go
  • openmeter/ledger/recognizer/service_test.go
  • openmeter/ledger/recognizer/sources.go
  • openmeter/ledger/testutils/lineage.go
  • openmeter/ledger/transactions/earnings.go
  • test/credits/recognition_lineage_test.go

Included review availability: Your plan provides up to 8 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

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

Changes

Allocation-aware earnings recognition

Layer / File(s) Summary
Lineage allocation metadata
openmeter/billing/charges/lineage/..., openmeter/ledger/testutils/lineage.go
Lineages now expose original allocation sort hints and transaction groups for all roots. Test lineage support preserves this allocation metadata.
Recognition source planning
openmeter/ledger/recognizer/sources.go, openmeter/ledger/transactions/earnings.go
Recognition selects accrued sources by allocation, funding route, charge IDs, and backfill state. Transaction resolution accepts validated caller-selected sources.
Planned recognition execution
openmeter/ledger/recognizer/recognize.go
The recognizer posts the planned amount and sources, then closes and recreates only the selected lineage segments.
Recognition validation and coverage
openmeter/ledger/recognizer/service_test.go, openmeter/ledger/chargeadapter/*_test.go, test/credits/recognition_lineage_test.go, openmeter/ledger/README.md
Tests cover accrued source isolation, paid backfills, refunds, retries, and deferred promotional credits. The ledger documentation describes the allocation rules.

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 cce64

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
Loading

Suggested reviewers: mark-vass-konghq, turip

🚥 Pre-merge checks | ✅ 4
✅ 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 clearly and concisely describes the main change: preserving source attribution in earnings lineage during ledger recognition.
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.
✨ 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 codex/fix-recognition-lineage-attribution

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.

Comment on lines +42 to +59
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)
}

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.

P2 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!

Fix in Claude Code Fix in Codex

@GAlexIHU
GAlexIHU merged commit 9ace5b2 into main Sep 8, 2026
28 of 31 checks passed
@GAlexIHU
GAlexIHU deleted the codex/fix-recognition-lineage-attribution branch September 8, 2026 13:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants