Skip to content

feat: add charge intent override layering - #4572

Merged
turip merged 6 commits into
mainfrom
feat/flat-fee-override-support
Jun 25, 2026
Merged

turip merged 6 commits into
mainfrom
feat/flat-fee-override-support

Conversation

@turip

@turip turip commented Jun 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Introduces explicit intent layering for flat-fee and usage-based charges so the persisted subscription/base intent can coexist with a customer-facing override layer.

Domain Rules

  • Flat-fee and usage-based charges now expose overridable intents with a base layer and optional override layer.
  • Customer-facing and ledger-facing paths should read effective intent values through field-specific getters.
  • Subscription sync and adapter persistence should keep targeting the base intent so API overrides do not feed back into subscription-owned state.
  • GetEffectiveIntent() remains available for mapping boundaries, but field-specific getters are preferred when only a few values are needed.

Notes

  • Updates charge service, adapter, API mapping, ledger adapter, and subscription-sync call sites to use the intended base/effective access pattern.
  • Updates the billing and charges skills with the new intent-layering guidance.

Validation

  • make lint
  • make test-nocache

Summary by CodeRabbit

  • Bug Fixes
    • Billing charges now consistently derive customer, currency, settlement mode, service periods, invoice timing, tax, discounts, and feature metadata from effective intent values across invoices, credits, previews, rating, allocation, and ledger postings.
    • Improved charge override and charge deletion behavior, including subscription item ID updates and more reliable reconciliation/repair for subscription sync persisted state.
    • Updated API charge conversion to use effective intent details for flat-fee and usage-based charges.
  • Documentation
    • Refreshed guidance on “base intent” vs “effective intent” usage for charge-backed subscription sync state and intent layer access rules.

@turip
turip requested a review from a team as a code owner June 25, 2026 18:20
@coderabbitai

coderabbitai Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Review 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: Pro

Run ID: 5a9b71f0-ab47-455b-bd04-5a6027f9b3df

📥 Commits

Reviewing files that changed from the base of the PR and between 3fc9c43 and ec38def.

📒 Files selected for processing (2)
  • openmeter/billing/charges/flatfee/adapter/intentoverride.go
  • openmeter/billing/charges/flatfee/charge.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • openmeter/billing/charges/flatfee/adapter/intentoverride.go
  • openmeter/billing/charges/flatfee/charge.go

📝 Walkthrough

Walkthrough

The PR updates charge intent handling to use layered base and effective getters across billing adapters, services, subscription sync, ledger, API conversion, and tests. It also changes override creation and deletion paths to pass explicit mutable override fields.

Changes

Layered charge intent refactor

Layer / File(s) Summary
Intent contracts and API mapping
.agents/skills/*, api/v3/handlers/customers/charges/convert.go, openmeter/billing/charges/charge.go, openmeter/billing/charges/flatfee/charge.go, openmeter/billing/charges/usagebased/charge.go, openmeter/billing/charges/flatfee/adapter.go, openmeter/billing/charges/usagebased/adapter.go
Docs, intent model helpers, adapter contracts, and API charge conversion now use base and effective intent accessors and the new overridable wrapper layout.
Flat-fee adapter and runtime
openmeter/billing/charges/flatfee/adapter/charge.go, openmeter/billing/charges/flatfee/adapter/intentoverride.go, openmeter/billing/charges/flatfee/adapter/mapper.go, openmeter/billing/charges/flatfee/service/*
Flat-fee override creation, deletion, DB hydration, charge creation, and state-machine flows now use explicit override payloads, rebuilt base intents, and effective intent getters.
Usage-based adapter and runtime
openmeter/billing/charges/usagebased/adapter/*, openmeter/billing/charges/usagebased/service/*
Usage-based override creation, deletion, DB hydration, charge creation, rating, run scheduling, and trigger flows now use explicit override payloads, getter-based base intents, and effective intent accessors.
Shared charge service runtime
openmeter/billing/charges/service/create.go, openmeter/billing/charges/service/*_test.go, openmeter/billing/charges/testutils/handlers.go, test/credits/*
Shared charge service code and tests now read settlement mode, service periods, payment terms, currencies, feature keys, customer IDs, and tax data through intent getters across creation, credits, rating, tax, truncation, and end-to-end credit flows.
Subscription sync, ledger, and balance
openmeter/billing/worker/subscriptionsync/service/..., openmeter/ledger/chargeadapter/..., openmeter/ledger/customerbalance/...
Subscription sync persisted-state loading and repair, ledger charge adapters, and customer-balance calculations now cache base intents or use intent getters for subscription, unique reference, tax, currency, feature, and timing data.

Sequence Diagram(s)

sequenceDiagram
  participant flatfeeCreateChargeOverride as flatfee.CreateChargeOverride
  participant flatfeeCreateIntentOverride as flatfee.createIntentOverride
  participant entdbChargeFlatFeeOverride as entdb.ChargeFlatFeeOverride
  participant flatfeeMapChargeBaseFromDB as flatfee.MapChargeBaseFromDB
  flatfeeCreateChargeOverride->>flatfeeCreateIntentOverride: validate override
  flatfeeCreateIntentOverride->>entdbChargeFlatFeeOverride: create.Save(ctx)
  entdbChargeFlatFeeOverride-->>flatfeeCreateChargeOverride: saved override row
  flatfeeCreateChargeOverride->>flatfeeMapChargeBaseFromDB: MapChargeBaseFromDB(dbCharge)
  flatfeeMapChargeBaseFromDB-->>flatfeeCreateChargeOverride: ChargeBase
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • openmeterio/openmeter#4571: It refactors and consumes the same layered intent model across charge, API, and service code paths.
  • openmeterio/openmeter#4556: It changes the flat-fee and usage-based intent override model and adapter wiring used by the same adapter files.
  • openmeterio/openmeter#4376: It touches subscription-sync repair logic that now rebuilds charge intents through base and override layers.

Suggested labels

release-note/feature, area/billing

Suggested reviewers

  • tothandras
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.06% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 matches the PR’s main change: introducing explicit charge intent override layering.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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/flat-fee-override-support

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.

@turip turip added release-note/feature Release note: Exciting New Features area/billing labels Jun 25, 2026
@turip turip changed the title Add charge intent override layering feat: add charge intent override layering Jun 25, 2026
@greptile-apps

greptile-apps Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds explicit base and override intent layers for charge-backed billing. The main changes are:

  • New intent accessors for base and effective charge fields.
  • Adapter updates that persist base intent rows and override rows separately.
  • API, ledger, and customer-balance reads moved to customer-facing effective values.
  • Subscription-sync persisted-state reads moved toward base intent values.

Confidence Score: 4/5

This is close, but the charge layering bugs should be fixed before merging.

  • Usage-based feature overrides can still rate against the base feature.
  • Subscription-sync extend and shrink patches can update customer-facing overrides instead of subscription-owned base state.

openmeter/billing/charges/usagebased/charge.go; openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go; openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go

Important Files Changed

Filename Overview
openmeter/billing/charges/usagebased/charge.go Adds the usage-based intent layering API, but created charges can still resolve usage against the base feature when an override changes the feature key.
openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go Builds subscription-sync extend and shrink patches for usage-based charges without a base-layer target.
openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go Builds subscription-sync extend and shrink patches for flat-fee charges without a base-layer target.
openmeter/billing/charges/flatfee/charge.go Adds the flat-fee intent layering API and effective/base accessors used by downstream callers.
api/v3/handlers/customers/charges/convert.go Maps charge API responses from effective intent fields so overrides are visible to customers.
openmeter/ledger/chargeadapter/usagebased.go Moves usage-based ledger fields to the new intent accessors.
openmeter/ledger/chargeadapter/flatfee.go Moves flat-fee ledger fields to the new intent accessors.

Comments Outside Diff (2)

  1. openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go, line 56-61 (link)

    P1 Sync Patch Hits Override

    This subscription-sync patch still carries no target layer, and the usage-based state machine applies extend/shrink through MutateEffective. When a credit-then-invoice usage-based charge has a customer override, subscription sync writes the subscription-owned service period and invoice date into the override layer instead of the base layer. That changes the customer-facing override and leaves the base subscription state stale, so future syncs can keep reconciling the same charge incorrectly.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go
    Line: 56-61
    
    Comment:
    **Sync Patch Hits Override**
    
    This subscription-sync patch still carries no target layer, and the usage-based state machine applies extend/shrink through `MutateEffective`. When a credit-then-invoice usage-based charge has a customer override, subscription sync writes the subscription-owned service period and invoice date into the override layer instead of the base layer. That changes the customer-facing override and leaves the base subscription state stale, so future syncs can keep reconciling the same charge incorrectly.
    
    How can I resolve this? If you propose a fix, please make it concise.

    Fix in Claude Code Fix in Codex

  2. openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go, line 56-61 (link)

    P1 Sync Patch Hits Override

    This subscription-sync patch still carries no target layer, and the flat-fee state machine applies extend/shrink through MutateEffective. When a credit-then-invoice flat-fee charge has a customer override, subscription sync writes the subscription-owned service period and invoice date into the override layer instead of the base layer. That changes the customer-facing override and leaves the base subscription state stale, so future syncs can keep reconciling the same charge incorrectly.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go
    Line: 56-61
    
    Comment:
    **Sync Patch Hits Override**
    
    This subscription-sync patch still carries no target layer, and the flat-fee state machine applies extend/shrink through `MutateEffective`. When a credit-then-invoice flat-fee charge has a customer override, subscription sync writes the subscription-owned service period and invoice date into the override layer instead of the base layer. That changes the customer-facing override and leaves the base subscription state stale, so future syncs can keep reconciling the same charge incorrectly.
    
    How can I resolve this? If you propose a fix, please make it concise.

    Fix in Claude Code Fix in Codex

Fix All in Claude Code Fix All in Codex

Prompt To Fix All With AI
Fix the following 3 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 3
openmeter/billing/charges/usagebased/charge.go:153
**Feature Override Ignored**

When a usage-based charge is still `created`, feature resolution now returns `GetBaseIntent().FeatureKey`. If the charge already has an override with a different `FeatureKey`, `ResolveFeatureMeter` and the totals/rating paths that use `GetFeatureKeyOrID` still resolve the base feature. The customer-facing API and ledger filters can show the effective feature while the charge rates usage from the base feature, producing balances for the wrong meter.

### Issue 2 of 3
openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go:56-61
**Sync Patch Hits Override**

This subscription-sync patch still carries no target layer, and the usage-based state machine applies extend/shrink through `MutateEffective`. When a credit-then-invoice usage-based charge has a customer override, subscription sync writes the subscription-owned service period and invoice date into the override layer instead of the base layer. That changes the customer-facing override and leaves the base subscription state stale, so future syncs can keep reconciling the same charge incorrectly.

### Issue 3 of 3
openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go:56-61
**Sync Patch Hits Override**

This subscription-sync patch still carries no target layer, and the flat-fee state machine applies extend/shrink through `MutateEffective`. When a credit-then-invoice flat-fee charge has a customer override, subscription sync writes the subscription-owned service period and invoice date into the override layer instead of the base layer. That changes the customer-facing override and leaves the base subscription state stale, so future syncs can keep reconciling the same charge incorrectly.

Reviews (3): Last reviewed commit: "fix: validate flat fee override deletion" | Re-trigger Greptile

@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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
openmeter/billing/charges/usagebased/charge.go (1)

144-162: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Use the effective feature key when an override exists.

GetFeatureKeyOrID() is used by runtime paths like current totals/triggers, but it falls back to the base feature key for created/deleted charges and State.FeatureID for active charges. If an override changes FeatureKey, the API can show the effective feature while rating/current totals still resolve the base feature.

Proposed effective-key fallback
 func (c Charge) GetFeatureKeyOrID() ref.IDOrKey {
-	// TODO: if API edits can override FeatureKey, keep State.FeatureID in sync
-	// with the effective key. State.FeatureID is the persisted resolved feature
-	// snapshot used by active charges; created/deleted fallbacks resolve by key.
+	if c.Intent.HasOverrideLayer() {
+		return ref.IDOrKey{
+			Key: c.Intent.GetEffectiveFeatureKey(),
+		}
+	}
+
+	// State.FeatureID is the persisted resolved feature snapshot used by active
+	// charges; created/deleted fallbacks resolve by key.
 	switch c.Status {
 	case StatusCreated:
 		return ref.IDOrKey{
-			Key: c.Intent.GetBaseIntent().FeatureKey,
+			Key: c.Intent.GetEffectiveFeatureKey(),
 		}
@@
 
 		return ref.IDOrKey{
-			Key: c.Intent.GetBaseIntent().FeatureKey,
+			Key: c.Intent.GetEffectiveFeatureKey(),
 		}
🤖 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/charge.go` around lines 144 - 162,
GetFeatureKeyOrID currently resolves created/deleted charges from
Intent.GetBaseIntent().FeatureKey, which ignores any overridden feature key and
can cause runtime paths to use the base feature instead of the effective one.
Update Charge.GetFeatureKeyOrID to prefer the effective feature key when
present, using the existing charge state/intended feature fields alongside the
current Status handling, and only fall back to State.FeatureID or the base key
when no override is available.
openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.go (1)

106-113: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Load charges by base deletion state, not effective deletion state.

loadChargesForSubscription() still relies on the default ListCharges filtering here, so an override-only delete can hide a charge whose base intent is still subscription-owned. That gives reconciliation an incomplete persisted snapshot and can drive the wrong create/delete plan. I'd include deleted charges in this load and filter locally on the base intent's deleted-at state instead.

🤖 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/worker/subscriptionsync/service/persistedstate/loader.go`
around lines 106 - 113, The charge loading in loadChargesForSubscription still
uses the default ListCharges filtering, which can hide subscription-owned
charges when only an override marks them deleted. Update the ListCharges call in
persistedstate.Loader to load charges without relying on effective deleted-state
filtering, then apply the deletion check locally using the base intent’s
deleted-at state so reconciliation sees the full persisted snapshot.
openmeter/billing/charges/usagebased/service/rating/service_test.go (1)

425-513: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Please add one real override-layer rating case.

These tests still build a base-only intent and then call effective getters on top of it, so they never exercise the new behavior when an override actually changes the service period. A case with a prior realization before an overridden ServicePeriod.From would give this refactor much better protection. As per path instructions, **/*_test.go: Make sure the tests are comprehensive and cover the changes.

🤖 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/rating/service_test.go` around
lines 425 - 513, The current helpers in newGetDetailedRatingForUsageFixture and
newDetailedRatingTestRun only exercise the base intent path, so add one real
override-layer rating test that uses an overridden ServicePeriod.From. Create a
fixture where an override changes the service period and include a prior
realization run before that overridden start time, then assert the detailed
rating behavior uses the overridden period correctly. Reuse the existing test
builders in service_test.go so the new case directly covers the new
override-layer behavior.

Source: Path instructions

openmeter/billing/charges/usagebased/service/rating/details.go (1)

220-256: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Filter prior realizations that predate the effective window.

Line 220 now seeds every prior-period snapshot from the current effective ServicePeriod.From. If an override moves that start forward, older persisted runs can still pass eligibleRealizations and then produce snapshot ranges where From is after realization.ServicePeriodTo. That will skew period-preserving rerates for charges with historical runs under the base intent. Please either exclude realizations before the effective window or derive each prior snapshot’s lower bound from run history instead of the current effective start.

🤖 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/rating/details.go` around lines
220 - 256, The prior-period snapshot logic in details.go is using the current
effective service-period start for every realization, which can create invalid
cumulative ranges for realizations that occurred before an override moved the
window forward. Update the loop in the rating details flow so it either skips
`EligibleRealizations` whose `ServicePeriodTo` predates
`Charge.Intent.GetEffectiveServicePeriod().From`, or derives each snapshot’s
lower bound from the realization/run history instead of always using the current
effective start. Make the fix around `snapshotQuantity` and the `priorPeriods`
construction in the same function.
🧹 Nitpick comments (9)
openmeter/billing/charges/flatfee/adapter/charge.go (1)

121-124: 🗄️ Data Integrity & Integration | 🔵 Trivial

Switch to Only(ctx) to enforce data integrity

Since the schema enforces a unique (namespace, charge_id) constraint on the ChargeFlatFeeOverride table, using First(ctx) risks silently ignoring duplicate rows if one were to slip through. Let's use Only(ctx) here to match the pattern in updateIntentOverride and ensure any potential data anomalies are caught immediately rather than silently consumed.

Suggested fix
 		override, err := tx.db.ChargeFlatFeeOverride.Query().
 			Where(dbchargeflatfeeoverride.NamespaceEQ(charge.Namespace)).
 			Where(dbchargeflatfeeoverride.ChargeIDEQ(charge.ID)).
-			First(ctx)
+			Only(ctx)
🤖 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/flatfee/adapter/charge.go` around lines 121 - 124,
The ChargeFlatFeeOverride lookup in `updateChargeOverride` still uses
`First(ctx)`, which can hide duplicate rows even though the `(namespace,
charge_id)` pair is meant to be unique. Change this query to `Only(ctx)` so the
behavior matches `updateIntentOverride` and duplicate data is surfaced
immediately. Keep the existing `NamespaceEQ` and `ChargeIDEQ` filters on
`tx.db.ChargeFlatFeeOverride.Query()` and only swap the terminal fetch method.
openmeter/ledger/chargeadapter/usagebased_test.go (1)

691-699: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep the run fixture tied to the charge under test.

newRunWithInvoiceUsage now reads an effective service period, but it pulls it from a brand-new charge instead of the charge used in the handler call. If a test changes the real charge's base or override service period later, the run fixture will drift and the scenario can still pass for the wrong reason. Passing the charge into this helper would keep the setup honest. As per path instructions, **/*_test.go: "Make sure the tests are comprehensive and cover the changes."

🤖 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/ledger/chargeadapter/usagebased_test.go` around lines 691 - 699,
The run fixture setup in newRunWithInvoiceUsage is decoupled from the actual
charge being tested because it calls newCharge(...) internally to derive the
ServicePeriod. Update this helper to accept the charge (or its intent) from the
calling test and use that charge’s effective service period when populating
invoicedusage.AccruedUsage, so the fixture stays aligned with the charge under
test and does not silently drift when service period overrides change.

Source: Path instructions

openmeter/ledger/chargeadapter/intent_test_helpers_test.go (1)

11-49: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add override-layer test helpers alongside the base-layer ones.

These helpers only rebuild the base intent/layer, but the handlers in this PR now read effective feature/tax/service-period values. Having a matching override-layer helper here would make it much easier to add a direct override-precedence test and catch any fallback to base-layer reads. As per path instructions, **/*_test.go: "Make sure the tests are comprehensive and cover the changes."

🤖 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/ledger/chargeadapter/intent_test_helpers_test.go` around lines 11 -
49, The test helpers currently only expose base-layer mutators like
editFlatFeeBaseIntentForTest, editFlatFeeBaseLayerForTest,
editUsageBasedBaseIntentForTest, and editUsageBasedBaseLayerForTest, so add
matching override-layer helpers for both flat-fee and usage-based charges. Reuse
the existing helper pattern to mutate the override layer on charge.Intent
instead of rebuilding only the base intent, and place the new helpers alongside
the existing ones so tests can easily verify effective feature, tax, and
service-period precedence.

Source: Path instructions

openmeter/billing/charges/flatfee/charge.go (1)

130-134: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Clone intent layers when entering OverridableIntent.

The new private fields are a nice boundary, but NewOverridableIntent still stores the caller-owned overrideLayer pointer and shallow-copies the base mutable fields. Cloning here keeps callers from mutating the aggregate outside Mutate()/validation.

Proposed boundary-clone tweak
 func (i Intent) AsOverridableIntent() OverridableIntent {
-	return OverridableIntent{
-		intent:         i.Intent,
-		baseLayer:      i.IntentMutableFields,
-		settlementMode: i.SettlementMode,
-	}
+	return NewOverridableIntent(i, nil)
 }
@@
 func NewOverridableIntent(baseIntent Intent, overrideLayer *IntentMutableFields) OverridableIntent {
+	var overrideLayerClone *IntentMutableFields
+	if overrideLayer != nil {
+		cloned := overrideLayer.Clone()
+		overrideLayerClone = &cloned
+	}
+
 	return OverridableIntent{
-		intent:         baseIntent.Intent,
-		baseLayer:      baseIntent.IntentMutableFields,
-		overrideLayer:  overrideLayer,
+		intent:         baseIntent.Intent.Clone(),
+		baseLayer:      baseIntent.IntentMutableFields.Clone(),
+		overrideLayer:  overrideLayerClone,
 		settlementMode: baseIntent.SettlementMode,
 	}
 }

Also applies to: 201-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/charges/flatfee/charge.go` around lines 130 - 134, Clone
the intent layers when building OverridableIntent so the aggregate does not
retain caller-owned mutable state. Update AsOverridableIntent and
NewOverridableIntent to deep-copy the base mutable fields and the overrideLayer
instead of assigning the incoming pointers directly, while keeping the existing
private-field boundary intact. Use the existing OverridableIntent construction
path and related intent/mutable-field symbols to ensure all layer state is owned
by the aggregate before Mutate() or validation runs.
openmeter/billing/charges/usagebased/charge.go (1)

202-206: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Clone intent layers when entering OverridableIntent.

Same encapsulation edge as flat-fee: the constructor stores the caller-owned override pointer and shallow-copies mutable fields, so outside code can mutate the aggregate without going through Mutate()/validation.

Proposed boundary-clone tweak
 func (i Intent) AsOverridableIntent() OverridableIntent {
-	return OverridableIntent{
-		intent:         i.Intent,
-		baseLayer:      i.IntentMutableFields,
-		settlementMode: i.SettlementMode,
-	}
+	return NewOverridableIntent(i, nil)
 }
@@
 func NewOverridableIntent(baseIntent Intent, overrideLayer *IntentMutableFields) OverridableIntent {
+	var overrideLayerClone *IntentMutableFields
+	if overrideLayer != nil {
+		cloned := overrideLayer.Clone()
+		overrideLayerClone = &cloned
+	}
+
 	return OverridableIntent{
-		intent:         baseIntent.Intent,
-		baseLayer:      baseIntent.IntentMutableFields,
-		overrideLayer:  overrideLayer,
+		intent:         baseIntent.Intent.Clone(),
+		baseLayer:      baseIntent.IntentMutableFields.Clone(),
+		overrideLayer:  overrideLayerClone,
 		settlementMode: baseIntent.SettlementMode,
 	}
 }

Also applies to: 247-253

🤖 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/charge.go` around lines 202 - 206,
`Intent.AsOverridableIntent` (and the matching flat-fee conversion path) is
leaking caller-owned mutable state by storing the override pointer and
shallow-copying mutable layers; update these constructors to deep-clone the
intent layers before returning `OverridableIntent` so changes can only go
through `Mutate()` and validation. Keep the fix localized to the
`AsOverridableIntent`/flat-fee boundary construction logic and ensure the cloned
`baseLayer`/override data no longer aliases the original intent.
openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go (1)

169-182: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Please add one fixture with a real override layer here.

Both helpers stop at .AsOverridableIntent(), so the existing charge only has a base layer. That means these tests still miss the layered case this refactor is protecting: subscription-sync replacements should update subscription-owned fields without wiping a customer override. As per path instructions, **/*_test.go: "Make sure the tests are comprehensive and cover the changes."

Also applies to: 226-237

🤖 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/worker/subscriptionsync/service/reconciler/patchcharge_test.go`
around lines 169 - 182, The test fixture in patchcharge_test needs a real
override layer, since the current helpers only build a base intent via
AsOverridableIntent and never exercise layered overrides. Update the charge
setup using the existing fixture helpers around charge, existingIntent, and
newChargePatchTestManagedResource so at least one case includes a customer
override layer on top of the base layer, and verify subscription-sync
replacement preserves override-owned fields while updating subscription-owned
fields.

Source: Path instructions

openmeter/billing/charges/service/taxcode_test.go (1)

101-139: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a tax-config case where base and effective diverge.

Right now all of these assertions call GetEffectiveTaxConfig(), but the fixtures still keep base and effective tax config identical. So a regression that accidentally reads the base layer would still pass. Adding one override-backed create/read, handler, or list case with a different effective tax config would actually pin down the layering behavior this PR is introducing. As per path instructions, **/*_test.go: "Make sure the tests are comprehensive and cover the changes." Based on PR objectives, the core contract here is base-vs-effective intent layering.

Also applies to: 197-235, 597-697, 902-920

🤖 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/service/taxcode_test.go` around lines 101 - 139,
The current tax-config tests only validate GetEffectiveTaxConfig() when base and
effective values are identical, so they won’t catch regressions that read the
wrong layer. Add at least one override-backed create/read or list/handler test
in taxcode_test.go where the intent’s base tax config and effective tax config
differ, then assert against the effective result via GetEffectiveTaxConfig()
while also verifying the base value is not used. Use the existing Create/Read
helpers and charge intent fixtures to pin down the base-vs-effective layering
behavior.

Source: Path instructions

openmeter/billing/charges/service/invoicable_test.go (1)

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

Add one override-backed lifecycle case.

These callbacks now assert through effective getters, but every changed fixture here still builds charges where base and effective service periods are the same. That means a fallback to base-layer reads in the runtime path would still pass. A single shrink/extend or override-backed case where GetEffectiveServicePeriod() differs from the persisted base would make this change much harder to regress. As per path instructions, **/*_test.go: "Make sure the tests are comprehensive and cover the changes." Based on PR objectives, the core contract here is base-vs-effective intent layering.

Also applies to: 1375-1375, 1558-1571, 1627-1627, 2466-2466, 2640-2640, 2719-2719, 2803-2803

🤖 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/service/invoicable_test.go` at line 1272, Add a
dedicated lifecycle test case in invoicable_test.go that uses an override-backed
charge intent where GetEffectiveServicePeriod() differs from the persisted base
ServicePeriod, so the callbacks are validated against effective intent data
rather than base-layer reads. Update one of the existing fixture paths around
the invoicable lifecycle assertions to shrink or extend the service period
through the effective getter and verify the downstream callbacks still use the
effective values. Use the existing Charge.Intent and GetEffectiveServicePeriod
symbols to place the new case alongside the current base/effective period
assertions.

Source: Path instructions

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

310-335: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Please add one override-backed fixture here.

This helper always returns base == effective, so the updated shrink/trigger tests still pass even if the runtime accidentally falls back to BaseLayer reads. A small variant with different override ServicePeriod and InvoiceAt values would make these tests actually cover the layering behavior this PR is changing.

As per path instructions, **/*_test.go: "Make sure the tests are comprehensive and cover the changes."

🤖 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/creditheninvoice_test.go` around
lines 310 - 335, The helper newUsageBasedIntentForCreditThenInvoiceTest
currently always produces an intent where base and effective values are
identical, so it does not exercise override-layer reads. Add one override-backed
fixture alongside this helper by varying the override IntentMutableFields values
such as ServicePeriod and InvoiceAt while keeping the same intent shape, so the
shrink/trigger tests in creditheninvoice_test.go verify the layering behavior
through usagebased.Intent.AsOverridableIntent rather than passing with BaseLayer
fallbacks.

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.

Inline comments:
In `@openmeter/billing/charges/flatfee/adapter/charge.go`:
- Around line 66-72: The flat-fee charge update path is still passing
unsupported scheduling data through chargemeta.UpdateInput. In the adapter’s
charge update flow, remove AdvanceAfter from the payload built in
chargemeta.Update() for flat-fee charges so the update only includes fields this
charge type supports; keep the rest of the metadata mapping intact.

In `@openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go`:
- Around line 93-96: The delete patch path in chargePatchCollection.AddDelete
still creates a whole-charge delete without any base-vs-override selector, so
subscription sync can target the wrong layer. Update AddDelete and the related
patch creation path it shares with the other delete flow to carry the charge
intent target through chargesmeta.NewPatchDelete (or an equivalent delete
payload) so the reconciler can explicitly delete the base intent layer instead
of a customer override. Use the existing chargePatchCollection, AddDelete, and
any shared delete helper/constructor symbols to keep both delete paths
consistent.

---

Outside diff comments:
In `@openmeter/billing/charges/usagebased/charge.go`:
- Around line 144-162: GetFeatureKeyOrID currently resolves created/deleted
charges from Intent.GetBaseIntent().FeatureKey, which ignores any overridden
feature key and can cause runtime paths to use the base feature instead of the
effective one. Update Charge.GetFeatureKeyOrID to prefer the effective feature
key when present, using the existing charge state/intended feature fields
alongside the current Status handling, and only fall back to State.FeatureID or
the base key when no override is available.

In `@openmeter/billing/charges/usagebased/service/rating/details.go`:
- Around line 220-256: The prior-period snapshot logic in details.go is using
the current effective service-period start for every realization, which can
create invalid cumulative ranges for realizations that occurred before an
override moved the window forward. Update the loop in the rating details flow so
it either skips `EligibleRealizations` whose `ServicePeriodTo` predates
`Charge.Intent.GetEffectiveServicePeriod().From`, or derives each snapshot’s
lower bound from the realization/run history instead of always using the current
effective start. Make the fix around `snapshotQuantity` and the `priorPeriods`
construction in the same function.

In `@openmeter/billing/charges/usagebased/service/rating/service_test.go`:
- Around line 425-513: The current helpers in
newGetDetailedRatingForUsageFixture and newDetailedRatingTestRun only exercise
the base intent path, so add one real override-layer rating test that uses an
overridden ServicePeriod.From. Create a fixture where an override changes the
service period and include a prior realization run before that overridden start
time, then assert the detailed rating behavior uses the overridden period
correctly. Reuse the existing test builders in service_test.go so the new case
directly covers the new override-layer behavior.

In `@openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.go`:
- Around line 106-113: The charge loading in loadChargesForSubscription still
uses the default ListCharges filtering, which can hide subscription-owned
charges when only an override marks them deleted. Update the ListCharges call in
persistedstate.Loader to load charges without relying on effective deleted-state
filtering, then apply the deletion check locally using the base intent’s
deleted-at state so reconciliation sees the full persisted snapshot.

---

Nitpick comments:
In `@openmeter/billing/charges/flatfee/adapter/charge.go`:
- Around line 121-124: The ChargeFlatFeeOverride lookup in
`updateChargeOverride` still uses `First(ctx)`, which can hide duplicate rows
even though the `(namespace, charge_id)` pair is meant to be unique. Change this
query to `Only(ctx)` so the behavior matches `updateIntentOverride` and
duplicate data is surfaced immediately. Keep the existing `NamespaceEQ` and
`ChargeIDEQ` filters on `tx.db.ChargeFlatFeeOverride.Query()` and only swap the
terminal fetch method.

In `@openmeter/billing/charges/flatfee/charge.go`:
- Around line 130-134: Clone the intent layers when building OverridableIntent
so the aggregate does not retain caller-owned mutable state. Update
AsOverridableIntent and NewOverridableIntent to deep-copy the base mutable
fields and the overrideLayer instead of assigning the incoming pointers
directly, while keeping the existing private-field boundary intact. Use the
existing OverridableIntent construction path and related intent/mutable-field
symbols to ensure all layer state is owned by the aggregate before Mutate() or
validation runs.

In `@openmeter/billing/charges/service/invoicable_test.go`:
- Line 1272: Add a dedicated lifecycle test case in invoicable_test.go that uses
an override-backed charge intent where GetEffectiveServicePeriod() differs from
the persisted base ServicePeriod, so the callbacks are validated against
effective intent data rather than base-layer reads. Update one of the existing
fixture paths around the invoicable lifecycle assertions to shrink or extend the
service period through the effective getter and verify the downstream callbacks
still use the effective values. Use the existing Charge.Intent and
GetEffectiveServicePeriod symbols to place the new case alongside the current
base/effective period assertions.

In `@openmeter/billing/charges/service/taxcode_test.go`:
- Around line 101-139: The current tax-config tests only validate
GetEffectiveTaxConfig() when base and effective values are identical, so they
won’t catch regressions that read the wrong layer. Add at least one
override-backed create/read or list/handler test in taxcode_test.go where the
intent’s base tax config and effective tax config differ, then assert against
the effective result via GetEffectiveTaxConfig() while also verifying the base
value is not used. Use the existing Create/Read helpers and charge intent
fixtures to pin down the base-vs-effective layering behavior.

In `@openmeter/billing/charges/usagebased/charge.go`:
- Around line 202-206: `Intent.AsOverridableIntent` (and the matching flat-fee
conversion path) is leaking caller-owned mutable state by storing the override
pointer and shallow-copying mutable layers; update these constructors to
deep-clone the intent layers before returning `OverridableIntent` so changes can
only go through `Mutate()` and validation. Keep the fix localized to the
`AsOverridableIntent`/flat-fee boundary construction logic and ensure the cloned
`baseLayer`/override data no longer aliases the original intent.

In `@openmeter/billing/charges/usagebased/service/creditheninvoice_test.go`:
- Around line 310-335: The helper newUsageBasedIntentForCreditThenInvoiceTest
currently always produces an intent where base and effective values are
identical, so it does not exercise override-layer reads. Add one override-backed
fixture alongside this helper by varying the override IntentMutableFields values
such as ServicePeriod and InvoiceAt while keeping the same intent shape, so the
shrink/trigger tests in creditheninvoice_test.go verify the layering behavior
through usagebased.Intent.AsOverridableIntent rather than passing with BaseLayer
fallbacks.

In
`@openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go`:
- Around line 169-182: The test fixture in patchcharge_test needs a real
override layer, since the current helpers only build a base intent via
AsOverridableIntent and never exercise layered overrides. Update the charge
setup using the existing fixture helpers around charge, existingIntent, and
newChargePatchTestManagedResource so at least one case includes a customer
override layer on top of the base layer, and verify subscription-sync
replacement preserves override-owned fields while updating subscription-owned
fields.

In `@openmeter/ledger/chargeadapter/intent_test_helpers_test.go`:
- Around line 11-49: The test helpers currently only expose base-layer mutators
like editFlatFeeBaseIntentForTest, editFlatFeeBaseLayerForTest,
editUsageBasedBaseIntentForTest, and editUsageBasedBaseLayerForTest, so add
matching override-layer helpers for both flat-fee and usage-based charges. Reuse
the existing helper pattern to mutate the override layer on charge.Intent
instead of rebuilding only the base intent, and place the new helpers alongside
the existing ones so tests can easily verify effective feature, tax, and
service-period precedence.

In `@openmeter/ledger/chargeadapter/usagebased_test.go`:
- Around line 691-699: The run fixture setup in newRunWithInvoiceUsage is
decoupled from the actual charge being tested because it calls newCharge(...)
internally to derive the ServicePeriod. Update this helper to accept the charge
(or its intent) from the calling test and use that charge’s effective service
period when populating invoicedusage.AccruedUsage, so the fixture stays aligned
with the charge under test and does not silently drift when service period
overrides change.
🪄 Autofix (Beta)

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

Run ID: 018deef0-45e2-48bb-8ac1-343a9ada6c91

📥 Commits

Reviewing files that changed from the base of the PR and between 18e5c91 and 6c52b98.

📒 Files selected for processing (79)
  • .agents/skills/billing/SKILL.md
  • .agents/skills/charges/SKILL.md
  • api/v3/handlers/customers/charges/convert.go
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/flatfee/adapter.go
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/flatfee/adapter/detailedline_test.go
  • openmeter/billing/charges/flatfee/adapter/intentoverride.go
  • openmeter/billing/charges/flatfee/adapter/intentoverride_test.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go
  • openmeter/billing/charges/flatfee/adapter/realizationrun_test.go
  • openmeter/billing/charges/flatfee/charge.go
  • openmeter/billing/charges/flatfee/service/create.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/creditsonly.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/flatfee/service/realizations/creditsonly.go
  • openmeter/billing/charges/flatfee/service/realizations/credittheninvoice.go
  • openmeter/billing/charges/flatfee/service/realizations/invoiceaccrued.go
  • openmeter/billing/charges/flatfee/service/realizations/preview.go
  • openmeter/billing/charges/flatfee/service/realizations/service.go
  • openmeter/billing/charges/flatfee/service/statemachine.go
  • openmeter/billing/charges/flatfee/service/triggers.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/featureid_test.go
  • openmeter/billing/charges/service/handlers_test.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/service/lineage_test.go
  • openmeter/billing/charges/service/pendinglines_test.go
  • openmeter/billing/charges/service/taxcode_test.go
  • openmeter/billing/charges/service/truncation_test.go
  • openmeter/billing/charges/testutils/handlers.go
  • openmeter/billing/charges/usagebased/adapter.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/detailedline_test.go
  • openmeter/billing/charges/usagebased/adapter/intentoverride.go
  • openmeter/billing/charges/usagebased/adapter/intentoverride_test.go
  • openmeter/billing/charges/usagebased/adapter/mapper.go
  • openmeter/billing/charges/usagebased/charge.go
  • openmeter/billing/charges/usagebased/service/create.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice_test.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/currenttotals.go
  • openmeter/billing/charges/usagebased/service/get.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/service/rating/details.go
  • openmeter/billing/charges/usagebased/service/rating/quantitysnapshot.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/charges/usagebased/service/rating/totals.go
  • openmeter/billing/charges/usagebased/service/run/create.go
  • openmeter/billing/charges/usagebased/service/run/credits.go
  • openmeter/billing/charges/usagebased/service/run/payment_test.go
  • openmeter/billing/charges/usagebased/service/run/preview.go
  • openmeter/billing/charges/usagebased/service/statemachine.go
  • openmeter/billing/charges/usagebased/service/triggers.go
  • openmeter/billing/worker/subscriptionsync/service/base_test.go
  • openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go
  • openmeter/billing/worker/subscriptionsync/service/persistedstate/item.go
  • openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go
  • openmeter/billing/worker/subscriptionsync/service/repair.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • openmeter/ledger/chargeadapter/annotations.go
  • openmeter/ledger/chargeadapter/flatfee.go
  • openmeter/ledger/chargeadapter/flatfee_test.go
  • openmeter/ledger/chargeadapter/intent_test_helpers_test.go
  • openmeter/ledger/chargeadapter/usagebased.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
  • openmeter/ledger/customerbalance/service.go
  • openmeter/ledger/customerbalance/service_test.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • openmeter/ledger/customerbalance/transactions.go
  • test/credits/credit_then_invoice_test.go
  • test/credits/rating_test.go
  • test/credits/sanity_test.go

@turip

turip commented Jun 25, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai The subscription-sync deleted-state finding is already intentionally captured as a TODO at openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.go next to the ListCharges call. The TODO says charge listing for subscription sync should filter by the base intent deleted-at state because effective DeletedAt can come from API overrides and hide charges whose subscription-owned base intent still needs reconciliation. Please check nearby TODO comments before posting redundant outside-diff findings as actionable comments.

@coderabbitai

coderabbitai Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@turip Good catch — thanks for the clarification. You're right: that concern is already intentionally tracked by the TODO in openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.go next to ListCharges, so my outside-diff finding was redundant. I’ll treat that as covered and be more careful to check nearby TODOs before raising it again.

(・×・)


✏️ Learnings added
Learnt from: turip
URL: https://github.com/openmeterio/openmeter/pull/4572

Timestamp: 2026-06-25T18:50:21.591Z
Learning: In `openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.go`, there is an intentional TODO next to the `ListCharges` call stating that subscription sync should filter charge listing by the base intent deleted-at state, because effective `DeletedAt` may come from API overrides and can hide charges whose subscription-owned base intent still needs reconciliation. For reviews in this area, nearby TODO comments should be checked before raising redundant outside-diff findings.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@turip

turip commented Jun 25, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai please be stricter about grounding review comments in the current diff and nearby code.

A few comments on this PR were based on stale assumptions or on gaps that are already explicitly documented as TODOs next to the relevant code. Going forward on this PR, please:

  • re-verify claims against the current pushed code before posting them,
  • skip actionable comments for known follow-up work that is already captured by nearby TODOs,
  • avoid outside-diff findings unless this PR introduces the concrete regression,
  • do not flag flat-fee AdvanceAfter metadata usage as unsupported unless the current code violates an explicit invariant.

In short: current-code evidence first, TODO-aware, fewer speculative findings. Really.

@coderabbitai

coderabbitai Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@turip Understood — that’s fair feedback.

I’ll tighten this up on #4572: re-check against the current pushed code, treat nearby TODOs as already-tracked follow-up work rather than fresh actionable findings, keep outside-diff comments to cases where this PR actually introduces the regression, and avoid flagging flat-fee AdvanceAfter metadata usage unless there’s a concrete invariant violation in the current code.

Current-code evidence first, TODO-aware, less speculation. Got it.

(•ᴗ•)🐇


✏️ Learnings added
Learnt from: turip
URL: https://github.com/openmeterio/openmeter/pull/4572

Timestamp: 2026-06-25T19:01:36.041Z
Learning: For PR reviews in this repository, review comments should be grounded in the current pushed diff and nearby code, with claims re-verified against the latest code before posting.

Learnt from: turip
URL: https://github.com/openmeterio/openmeter/pull/4572

Timestamp: 2026-06-25T19:01:36.041Z
Learning: When nearby TODO comments already capture known follow-up work in the relevant code, avoid posting redundant actionable review comments for that same gap unless the current PR changes its status or introduces a concrete regression.

Learnt from: turip
URL: https://github.com/openmeterio/openmeter/pull/4572

Timestamp: 2026-06-25T19:01:36.041Z
Learning: Avoid outside-diff findings in this repository unless the current PR introduces the specific regression being flagged.

Learnt from: turip
URL: https://github.com/openmeterio/openmeter/pull/4572

Timestamp: 2026-06-25T19:01:36.041Z
Learning: In code reviewing flat-fee charge flows in this repository, do not flag `AdvanceAfter` metadata usage as unsupported unless the current code violates an explicit invariant.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@turip

turip commented Jun 25, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai Fixed the First(ctx) -> Only(ctx) lookup nitpick in openmeter/billing/charges/flatfee/adapter/charge.go with commit 3fc9c43ab.

@coderabbitai

coderabbitai Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@turip Nice, thanks for fixing that and for calling out the commit.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

@turip
turip enabled auto-merge (squash) June 25, 2026 20:40
case StatusCreated:
return ref.IDOrKey{
Key: c.Intent.BaseLayer.FeatureKey,
Key: c.Intent.GetBaseIntent().FeatureKey,

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.

P1 Feature Override Ignored

When a usage-based charge is still created, feature resolution now returns GetBaseIntent().FeatureKey. If the charge already has an override with a different FeatureKey, ResolveFeatureMeter and the totals/rating paths that use GetFeatureKeyOrID still resolve the base feature. The customer-facing API and ledger filters can show the effective feature while the charge rates usage from the base feature, producing balances for the wrong meter.

Prompt To Fix With AI
This is a comment left during a code review.
Path: openmeter/billing/charges/usagebased/charge.go
Line: 153

Comment:
**Feature Override Ignored**

When a usage-based charge is still `created`, feature resolution now returns `GetBaseIntent().FeatureKey`. If the charge already has an override with a different `FeatureKey`, `ResolveFeatureMeter` and the totals/rating paths that use `GetFeatureKeyOrID` still resolve the base feature. The customer-facing API and ledger filters can show the effective feature while the charge rates usage from the base feature, producing balances for the wrong meter.

How can I resolve this? If you propose a fix, please make it concise.

Fix in Claude Code Fix in Codex

@turip
turip merged commit 3d4c7f0 into main Jun 25, 2026
41 of 42 checks passed
@turip
turip deleted the feat/flat-fee-override-support branch June 25, 2026 21:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants