Repository navigation
fix(usagebased): persist credits in CTI run details - #4793
Conversation
📝 WalkthroughWalkthroughUsage-based detailed lines now carry persisted credit-allocation metadata. Upsert calls use a structured input, credit-then-invoice flows apply credits before persistence, and fetch logic supports both current and legacy run data. ChangesDetailed-line contracts and transformations
Persistence and retrieval metadata
Settlement-aware service flow
Estimated code review effort: 3 (Moderate) | ~25 minutes Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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 |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openmeter/billing/charges/usagebased/adapter/detailedline_test.go (1)
358-403: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winConsider adding a test for the legacy CTI credit-migration path.
This suite covers the
DetailedLinesPresentflag thoroughly, but I don't see a test exercising the new dynamic-migration branch inFetchDetailedLines(CreditThenInvoice settlement + persistedDetailedLinesIncludeCreditAllocations=false→ appliesrun.CreditsAllocatedviaWithCreditsAppliedon read). That's genuinely new behavior added in this PR and worth a dedicated adapter-level test (seed a legacy row withdetailed_lines_include_credit_allocations=falseplus someCreditsAllocated, then assert the fetched lines reflect applied credits and the flag flips totruein-memory).🧪 Sketch of the missing scenario
func (s *DetailedLineAdapterSuite) TestFetchDetailedLinesAppliesLegacyCreditAllocations() { // given: a credit-then-invoice charge/run with detailed lines persisted // with detailed_lines_include_credit_allocations=false (legacy) and // non-zero CreditsAllocated on the run. // when: fetching detailed lines via GetByID. // then: fetched lines reflect the credits applied, and // DetailedLinesIncludeCreditAllocations is true on the in-memory realization. }As per path instructions, "Make sure the tests are comprehensive and cover the changes." Would you like me to draft this test?
🤖 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/usagebased/adapter/detailedline_test.go` around lines 358 - 403, Extend DetailedLineAdapterSuite with a dedicated TestFetchDetailedLinesAppliesLegacyCreditAllocations covering a CreditThenInvoice run whose persisted detailed_lines_include_credit_allocations is false and CreditsAllocated is non-zero. Seed persisted detailed lines, fetch through FetchDetailedLines, then assert the returned lines include credits via the existing WithCreditsApplied behavior and the in-memory DetailedLinesIncludeCreditAllocations flag is true.Source: Path instructions
🤖 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 `@openmeter/billing/charges/usagebased/adapter/detailedline_test.go`:
- Around line 358-403: Extend DetailedLineAdapterSuite with a dedicated
TestFetchDetailedLinesAppliesLegacyCreditAllocations covering a
CreditThenInvoice run whose persisted detailed_lines_include_credit_allocations
is false and CreditsAllocated is non-zero. Seed persisted detailed lines, fetch
through FetchDetailedLines, then assert the returned lines include credits via
the existing WithCreditsApplied behavior and the in-memory
DetailedLinesIncludeCreditAllocations flag is true.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 520ebdcb-0c24-4fa9-b439-4f336fd53b92
⛔ Files ignored due to path filters (9)
openmeter/ent/db/chargeusagebasedruns.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns/chargeusagebasedruns.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebasedruns_update.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/runtime.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (12)
openmeter/billing/charges/usagebased/adapter.goopenmeter/billing/charges/usagebased/adapter/detailedline.goopenmeter/billing/charges/usagebased/adapter/detailedline_test.goopenmeter/billing/charges/usagebased/adapter/mapper.goopenmeter/billing/charges/usagebased/detailedline.goopenmeter/billing/charges/usagebased/realizationrun.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditsonly.goopenmeter/billing/charges/usagebased/service/run/create.goopenmeter/ent/schema/chargesusagebased.gotools/migrate/migrations/20260727095118_usage_based_run_detailed_lines_credit_allocations.down.sqltools/migrate/migrations/20260727095118_usage_based_run_detailed_lines_credit_allocations.up.sql
Summary
credit_then_invoicerun detailed lines.credits_onlyrun detailed lines gross while retaining net run totals.Why
Usage-based CTI run totals already included allocated credits, but their persisted detailed lines remained gross. This made the run aggregate internally inconsistent and left readers unable to distinguish legacy gross details from the new credit-applied representation.
The representation marker preserves compatibility with existing rows, while read-time normalization lets callers consume a consistent current domain model without mutating historical data.
Validation
Summary by CodeRabbit
New Features
Bug Fixes
Database
Greptile Summary
Persists and exposes the credit-allocation representation of usage-based realization-run details.
Confidence Score: 5/5
The PR appears safe to merge, with no concrete blocking or independently actionable non-blocking defects identified.
Credit application is retry-safe because existing applications are reversed before authoritative allocations are reapplied, credits-only details remain gross, legacy normalization is marker-gated, and rating removes credits before gross-detail subtraction.
Important Files Changed
Flowchart
%%{init: {'theme': 'neutral'}}%% flowchart LR Rating[Gross rated detailed lines] --> Mode{Settlement mode} Mode -->|Credit then invoice| Apply[Apply run credit allocations] Mode -->|Credits only| Gross[Keep gross details] Apply --> Persist[Persist detailed lines and representation marker] Gross --> Persist Persist --> Read{Marker present?} Read -->|Current representation| Return[Return persisted details] Read -->|Legacy CTI representation| Normalize[Apply authoritative run credits at read time] Normalize --> ReturnReviews (1): Last reviewed commit: "fix(usagebased): persist credits in CTI ..." | Re-trigger Greptile
Context used: