Skip to content

fix: add charge discount correlation IDs - #4890

Merged
turip merged 2 commits into
mainfrom
feat/charge-discount-correlation-ids
Aug 9, 2026
Merged

turip merged 2 commits into
mainfrom
feat/charge-discount-correlation-ids

Conversation

@turip

@turip turip commented Aug 9, 2026 •

Copy link
Copy Markdown
Member

Summary

  • allocate stable correlation IDs when usage-based and flat-fee charge discounts enter or mutate an intent layer
  • normalize both base and override layers, with defensive persistence normalization for existing invalid entities
  • repair missing IDs only on active charge-backed gathering-line discount snapshots
  • cover charge-backed pending-line creation and the scoped SQL repair with regression tests

Root cause

billing.PercentageDiscount and billing.UsageDiscount extend product-catalog discounts with a correlation ID, but their promoted validators only validate the embedded commercial fields. Charge creation could therefore persist billing discounts without IDs. After charge-backed rating began consuming the persisted discounts directly, detailed-line generation rejected those entities with discount has no correlation ID.

Repair scope

The migration repairs only active billing_gathering_invoice_lines records where charge_id IS NOT NULL. For each present percentage or usage discount with a missing ID, it assigns an arbitrary generated ULID while preserving existing IDs. Standard invoice lines, charge rows, and override rows are intentionally not migrated.

New charge writes allocate IDs immediately. Existing base and override intents self-heal on their next persisted state-machine update because the charge and override adapters defensively upsert missing IDs at their write boundaries.

Impact

Existing affected gathering lines can be rated after migration. New and subsequently updated charge intents persist stable discount identities, and rerating, invoice projection, and corrections reuse those persisted IDs.

Validation

  • go test ./openmeter/billing -run 'Test.*Correlation' -count=1
  • go test ./openmeter/billing/charges/flatfee/service ./openmeter/billing/charges/usagebased/service -count=1
  • POSTGRES_HOST=127.0.0.1 go test ./tools/migrate -run TestBackfillChargeDiscountCorrelationIDs -count=1
  • make migrate-check-lint
  • make migrate-check-validate

@turip
turip requested a review from a team as a code owner August 9, 2026 15:38
@turip turip added kind/bug Something isn't working release-note/bug-fix Release note: Bug Fixes area/billing labels Aug 9, 2026
@coderabbitai

coderabbitai Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds stable correlation IDs for percentage and usage discounts. New charge writes assign missing IDs, existing eligible invoice lines receive a transactional backfill, and tests verify ID preservation through pending-line and invoice flows.

Changes

Discount correlation ID persistence

Layer / File(s) Summary
Discount correlation ID contract
openmeter/billing/discount.go, openmeter/billing/discount_test.go
Discount helpers clone discounts, preserve existing IDs, generate missing ULIDs, and remain idempotent without mutating the source value.
Charge write-path normalization
openmeter/billing/charges/flatfee/..., openmeter/billing/charges/usagebased/..., openmeter/billing/charges/service/pendinglines_test.go, openmeter/billing/charges/README.md
Charge creation, updates, overrides, and state-machine mutations upsert discount IDs before persistence. Tests verify propagation to pending and invoice lines.
Historical charge backfill
tools/migrate/migrations/20260809152600_backfill_charge_discount_correlation_ids.*, tools/migrate/charge_discount_correlation_ids_test.go
The migration generates missing IDs for eligible gathering invoice lines, preserves existing values, validates completion, and tests rerun idempotency.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ChargeIntent
  participant ChargeService
  participant ChargeAdapter
  participant PersistedCharge
  participant InvoiceLine
  ChargeIntent->>ChargeService: normalized intent
  ChargeService->>ChargeService: upsert discount correlation IDs
  ChargeService->>ChargeAdapter: create or mutate charge
  ChargeAdapter->>PersistedCharge: persist normalized discounts
  PersistedCharge->>InvoiceLine: propagate discount correlation ID
Loading

Possibly related PRs

Suggested reviewers: tothandras, borosr

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding correlation IDs to charge discounts.
✨ 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 feat/charge-discount-correlation-ids

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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
openmeter/billing/discount.go (1)

47-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the correlation ID contract.

Add Go doc comments for these helpers. State that they preserve an existing ID, generate an ID only when it is empty, and do not mutate the input value.

As per coding guidelines, "Document domain helpers whose names compress important business semantics, including observable behavior and why excluded cases are excluded."

Also applies to: 99-110, 203-207

🤖 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/discount.go` around lines 47 - 58, Add Go doc comments to
the correlation-ID helper methods, including
PercentageDiscount.UpsertCorrelationID and the corresponding helpers around the
referenced ranges. Document that each preserves an existing ID, generates one
only when the ID is empty, and returns a copy without mutating the input value.

Source: Coding guidelines

openmeter/billing/charges/usagebased/service/statemachine.go (1)

144-152: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Move discount-correlation normalization into a named helper.

The local closure applies a domain mutation to three intent-layer paths. Move this rule to a private named helper and keep the switch focused on layer selection. This makes the persistence invariant easier to find and test.

As per coding guidelines, do not hide meaningful domain translation inside local closures; use named helpers and reserve inline callbacks for obvious, tiny logic.

Also applies to: 156-169

🤖 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/service/statemachine.go` around lines
144 - 152, The local editWithDiscountCorrelationIDs closure should be replaced
with a private named helper that applies UpsertCorrelationIDs to
usagebased.IntentMutableFields after invoking the provided edit function. Update
all three intent-layer paths, including the switch cases around the referenced
closure, to call the named helper while keeping the switch focused on selecting
the appropriate layer.

Source: Coding guidelines

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

Inline comments:
In
`@tools/migrate/migrations/20260809152600_backfill_charge_discount_correlation_ids.up.sql`:
- Around line 8-34: Update the candidate SELECTs in
tools/migrate/migrations/20260809152600_backfill_charge_discount_correlation_ids.up.sql
(lines 8-34) to use l.id as correlation_id and select rows when the applicable
discount object exists, removing the requirement for a nested correlationID.
Update tools/migrate/charge_discount_correlation_ids_test.go (lines 29-41) to
expect source invoice-line IDs for repaired discounts, and add source discount
objects without correlation IDs in lines 102-118 to verify each invoice-line ID
is reused.

---

Nitpick comments:
In `@openmeter/billing/charges/usagebased/service/statemachine.go`:
- Around line 144-152: The local editWithDiscountCorrelationIDs closure should
be replaced with a private named helper that applies UpsertCorrelationIDs to
usagebased.IntentMutableFields after invoking the provided edit function. Update
all three intent-layer paths, including the switch cases around the referenced
closure, to call the named helper while keeping the switch focused on selecting
the appropriate layer.

In `@openmeter/billing/discount.go`:
- Around line 47-58: Add Go doc comments to the correlation-ID helper methods,
including PercentageDiscount.UpsertCorrelationID and the corresponding helpers
around the referenced ranges. Document that each preserves an existing ID,
generates one only when the ID is empty, and returns a copy without mutating the
input value.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 8a9515c1-8bec-4b9e-87d4-447a471d92cf

📥 Commits

Reviewing files that changed from the base of the PR and between a9a7283 and 55c8556.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (15)
  • openmeter/billing/charges/README.md
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/flatfee/adapter/intentoverride.go
  • openmeter/billing/charges/flatfee/service/create.go
  • openmeter/billing/charges/flatfee/service/statemachine.go
  • openmeter/billing/charges/service/pendinglines_test.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/intentoverride.go
  • openmeter/billing/charges/usagebased/service/create.go
  • openmeter/billing/charges/usagebased/service/statemachine.go
  • openmeter/billing/discount.go
  • openmeter/billing/discount_test.go
  • tools/migrate/charge_discount_correlation_ids_test.go
  • tools/migrate/migrations/20260809152600_backfill_charge_discount_correlation_ids.down.sql
  • tools/migrate/migrations/20260809152600_backfill_charge_discount_correlation_ids.up.sql

@turip

turip commented Aug 9, 2026

Copy link
Copy Markdown
Member Author

Review follow-up in 75e048c:

  • Added Go doc comments covering ID preservation, missing-ID allocation, copy semantics, and nil behavior.
  • Extracted named flat-fee and usage-based intent mutation helpers and routed base, existing-override, and new-override paths through them.
  • Narrowed the migration to active charge-backed gathering lines; the rationale and intentional disagreement with invoice-line ID reuse are documented in the CodeRabbit inline thread.

Focused Go tests, the PostgreSQL migration regression, Atlas validation, and Atlas lint all pass locally.

@turip
turip merged commit 42574e1 into main Aug 9, 2026
27 checks passed
@turip
turip deleted the feat/charge-discount-correlation-ids branch August 9, 2026 16:25
@tothandras

Copy link
Copy Markdown
Contributor

approved

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing kind/bug Something isn't working release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants