Skip to content

fix(usagebased): persist credits in CTI run details - #4793

Merged
turip merged 1 commit into
mainfrom
fix/usagebased-run-detailed-line-credits
Jul 27, 2026
Merged

turip merged 1 commit into
mainfrom
fix/usagebased-run-detailed-line-credits

Conversation

@turip

@turip turip commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Persist credit allocations in usage-based credit_then_invoice run detailed lines.
  • Keep credits_only run detailed lines gross while retaining net run totals.
  • Record the persisted detailed-line representation and normalize legacy CTI runs when read.

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

  • Focused usage-based Go tests
  • Focused usage-based Go vet
  • Go lint
  • Atlas migration validation and lint

Summary by CodeRabbit

  • New Features

    • Detailed usage lines now show how credit allocations affect charges.
    • Added support for applying credits to detailed line items while preserving original data.
    • Legacy runs are automatically adapted when credit allocation details are unavailable.
  • Bug Fixes

    • Improved retrieval and persistence of detailed usage lines.
    • Added clearer handling for runs without materialized detailed lines.
  • Database

    • Added storage for whether detailed lines include credit allocations.

Greptile Summary

Persists and exposes the credit-allocation representation of usage-based realization-run details.

  • Applies allocated credits before persisting credit-then-invoice detailed lines while retaining gross details for credits-only runs.
  • Adds a database representation marker and normalizes legacy credit-then-invoice details at read time.
  • Updates the realization-run adapter contract, domain models, generated Ent code, migration, and focused adapter tests.

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

Filename Overview
openmeter/billing/charges/usagebased/adapter/detailedline.go Persists the representation marker and normalizes unmarked legacy credit-then-invoice detailed lines during expansion.
openmeter/billing/charges/usagebased/detailedline.go Adds validated upsert input and retry-safe credit application over cloned detailed-line bases.
openmeter/billing/charges/usagebased/service/run/create.go Applies run allocations to newly created credit-then-invoice details before persisting them.
openmeter/billing/charges/usagebased/service/creditheninvoice.go Persists reconciled credit allocations in credit-then-invoice snapshots and marks their representation.
openmeter/billing/charges/usagebased/service/creditsonly.go Retains gross persisted details for credits-only runs while using the expanded upsert contract.
openmeter/ent/schema/chargesusagebased.go Adds the default-false detailed-line credit-allocation representation marker.
tools/migrate/migrations/20260727095118_usage_based_run_detailed_lines_credit_allocations.up.sql Adds the non-null representation marker with a legacy-compatible false default.

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

Reviews (1): Last reviewed commit: "fix(usagebased): persist credits in CTI ..." | Re-trigger Greptile

Context used:

@turip
turip requested a review from a team as a code owner July 27, 2026 11:02
@turip turip added release-note/bug-fix Release note: Bug Fixes area/billing labels Jul 27, 2026
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Detailed-line contracts and transformations

Layer / File(s) Summary
Structured input and credit application
openmeter/billing/charges/usagebased/adapter.go, openmeter/billing/charges/usagebased/detailedline.go, openmeter/billing/charges/usagebased/realizationrun.go
Adds validated upsert input, cloned credit-application logic, and realization-run metadata describing whether detailed lines include credit allocations.

Persistence and retrieval metadata

Layer / File(s) Summary
Persisted metadata and fetch compatibility
openmeter/billing/charges/usagebased/adapter/detailedline.go, openmeter/billing/charges/usagebased/adapter/mapper.go, openmeter/ent/schema/chargesusagebased.go, tools/migrate/migrations/*
Persists and maps the credit-allocation flag, restores it during fetches, and applies legacy credit allocations for eligible runs.
Adapter validation coverage
openmeter/billing/charges/usagebased/adapter/detailedline_test.go
Updates detailed-line adapter tests to use the structured upsert input.

Settlement-aware service flow

Layer / File(s) Summary
Credit-aware persistence
openmeter/billing/charges/usagebased/service/creditheninvoice.go, openmeter/billing/charges/usagebased/service/run/create.go
Applies allocated credits to detailed lines before persistence and updates in-memory run metadata.
Credits-only integration
openmeter/billing/charges/usagebased/service/creditsonly.go
Migrates the credits-only detailed-line upsert call to the structured input.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

Suggested labels: kind/refactor

Suggested reviewers: tothandras, galexihu, chrisgacsal

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly reflects the main change: persisting credit allocations in credit-then-invoice usage-based run details.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 fix/usagebased-run-detailed-line-credits

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.

@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 (1)
openmeter/billing/charges/usagebased/adapter/detailedline_test.go (1)

358-403: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Consider adding a test for the legacy CTI credit-migration path.

This suite covers the DetailedLinesPresent flag thoroughly, but I don't see a test exercising the new dynamic-migration branch in FetchDetailedLines (CreditThenInvoice settlement + persisted DetailedLinesIncludeCreditAllocations=false → applies run.CreditsAllocated via WithCreditsApplied on read). That's genuinely new behavior added in this PR and worth a dedicated adapter-level test (seed a legacy row with detailed_lines_include_credit_allocations=false plus some CreditsAllocated, then assert the fetched lines reflect applied credits and the flag flips to true in-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

📥 Commits

Reviewing files that changed from the base of the PR and between c582e04 and 76a10cb.

⛔ Files ignored due to path filters (9)
  • openmeter/ent/db/chargeusagebasedruns.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns/chargeusagebasedruns.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedruns_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (12)
  • openmeter/billing/charges/usagebased/adapter.go
  • openmeter/billing/charges/usagebased/adapter/detailedline.go
  • openmeter/billing/charges/usagebased/adapter/detailedline_test.go
  • openmeter/billing/charges/usagebased/adapter/mapper.go
  • openmeter/billing/charges/usagebased/detailedline.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/run/create.go
  • openmeter/ent/schema/chargesusagebased.go
  • tools/migrate/migrations/20260727095118_usage_based_run_detailed_lines_credit_allocations.down.sql
  • tools/migrate/migrations/20260727095118_usage_based_run_detailed_lines_credit_allocations.up.sql

@turip
turip merged commit 1210e1a into main Jul 27, 2026
28 of 31 checks passed
@turip
turip deleted the fix/usagebased-run-detailed-line-credits branch July 27, 2026 11:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants