Repository navigation
feat: add charge intent override layering - #4572
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughThe 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. ChangesLayered charge intent refactor
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
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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 |
Greptile SummaryThis PR adds explicit base and override intent layers for charge-backed billing. The main changes are:
Confidence Score: 4/5This is close, but the charge layering bugs should be fixed before merging.
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
|
There was a problem hiding this comment.
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 winUse 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 andState.FeatureIDfor active charges. If an override changesFeatureKey, 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 winLoad charges by base deletion state, not effective deletion state.
loadChargesForSubscription()still relies on the defaultListChargesfiltering 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 winPlease 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.Fromwould 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 winFilter 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 passeligibleRealizationsand then produce snapshot ranges whereFromis afterrealization.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 | 🔵 TrivialSwitch to
Only(ctx)to enforce data integritySince the schema enforces a unique
(namespace, charge_id)constraint on theChargeFlatFeeOverridetable, usingFirst(ctx)risks silently ignoring duplicate rows if one were to slip through. Let's useOnly(ctx)here to match the pattern inupdateIntentOverrideand 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 winKeep the run fixture tied to the charge under test.
newRunWithInvoiceUsagenow 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 winAdd 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 winClone intent layers when entering
OverridableIntent.The new private fields are a nice boundary, but
NewOverridableIntentstill stores the caller-ownedoverrideLayerpointer and shallow-copies the base mutable fields. Cloning here keeps callers from mutating the aggregate outsideMutate()/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 winClone 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 winPlease 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 winAdd 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 winAdd 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 winPlease 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 toBaseLayerreads. A small variant with different overrideServicePeriodandInvoiceAtvalues 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
📒 Files selected for processing (79)
.agents/skills/billing/SKILL.md.agents/skills/charges/SKILL.mdapi/v3/handlers/customers/charges/convert.goopenmeter/billing/charges/charge.goopenmeter/billing/charges/flatfee/adapter.goopenmeter/billing/charges/flatfee/adapter/charge.goopenmeter/billing/charges/flatfee/adapter/detailedline_test.goopenmeter/billing/charges/flatfee/adapter/intentoverride.goopenmeter/billing/charges/flatfee/adapter/intentoverride_test.goopenmeter/billing/charges/flatfee/adapter/mapper.goopenmeter/billing/charges/flatfee/adapter/realizationrun_test.goopenmeter/billing/charges/flatfee/charge.goopenmeter/billing/charges/flatfee/service/create.goopenmeter/billing/charges/flatfee/service/creditheninvoice.goopenmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/realizations/creditsonly.goopenmeter/billing/charges/flatfee/service/realizations/credittheninvoice.goopenmeter/billing/charges/flatfee/service/realizations/invoiceaccrued.goopenmeter/billing/charges/flatfee/service/realizations/preview.goopenmeter/billing/charges/flatfee/service/realizations/service.goopenmeter/billing/charges/flatfee/service/statemachine.goopenmeter/billing/charges/flatfee/service/triggers.goopenmeter/billing/charges/service/create.goopenmeter/billing/charges/service/featureid_test.goopenmeter/billing/charges/service/handlers_test.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/charges/service/lineage_test.goopenmeter/billing/charges/service/pendinglines_test.goopenmeter/billing/charges/service/taxcode_test.goopenmeter/billing/charges/service/truncation_test.goopenmeter/billing/charges/testutils/handlers.goopenmeter/billing/charges/usagebased/adapter.goopenmeter/billing/charges/usagebased/adapter/charge.goopenmeter/billing/charges/usagebased/adapter/detailedline_test.goopenmeter/billing/charges/usagebased/adapter/intentoverride.goopenmeter/billing/charges/usagebased/adapter/intentoverride_test.goopenmeter/billing/charges/usagebased/adapter/mapper.goopenmeter/billing/charges/usagebased/charge.goopenmeter/billing/charges/usagebased/service/create.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditheninvoice_test.goopenmeter/billing/charges/usagebased/service/creditsonly.goopenmeter/billing/charges/usagebased/service/currenttotals.goopenmeter/billing/charges/usagebased/service/get.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/charges/usagebased/service/rating/details.goopenmeter/billing/charges/usagebased/service/rating/quantitysnapshot.goopenmeter/billing/charges/usagebased/service/rating/service_test.goopenmeter/billing/charges/usagebased/service/rating/totals.goopenmeter/billing/charges/usagebased/service/run/create.goopenmeter/billing/charges/usagebased/service/run/credits.goopenmeter/billing/charges/usagebased/service/run/payment_test.goopenmeter/billing/charges/usagebased/service/run/preview.goopenmeter/billing/charges/usagebased/service/statemachine.goopenmeter/billing/charges/usagebased/service/triggers.goopenmeter/billing/worker/subscriptionsync/service/base_test.goopenmeter/billing/worker/subscriptionsync/service/creditsonly_test.goopenmeter/billing/worker/subscriptionsync/service/persistedstate/item.goopenmeter/billing/worker/subscriptionsync/service/persistedstate/loader.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge_test.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.goopenmeter/billing/worker/subscriptionsync/service/repair.goopenmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.goopenmeter/ledger/chargeadapter/annotations.goopenmeter/ledger/chargeadapter/flatfee.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/intent_test_helpers_test.goopenmeter/ledger/chargeadapter/usagebased.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/customerbalance/service.goopenmeter/ledger/customerbalance/service_test.goopenmeter/ledger/customerbalance/testenv_test.goopenmeter/ledger/customerbalance/transactions.gotest/credits/credit_then_invoice_test.gotest/credits/rating_test.gotest/credits/sanity_test.go
|
@coderabbitai The subscription-sync deleted-state finding is already intentionally captured as a TODO at |
|
Tip For best results, initiate chat on the files or code changes.
(・×・) ✏️ Learnings added
|
|
@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:
In short: current-code evidence first, TODO-aware, fewer speculative findings. Really. |
|
Tip For best results, initiate chat on the files or code changes.
I’ll tighten this up on Current-code evidence first, TODO-aware, less speculation. Got it. (•ᴗ•)🐇 ✏️ Learnings added
|
|
@coderabbitai Fixed the |
|
Tip For best results, initiate chat on the files or code changes.
If you found this review helpful, would you consider giving us a shout-out on X? Thank you for using CodeRabbit! |
| case StatusCreated: | ||
| return ref.IDOrKey{ | ||
| Key: c.Intent.BaseLayer.FeatureKey, | ||
| Key: c.Intent.GetBaseIntent().FeatureKey, |
There was a problem hiding this comment.
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.
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
GetEffectiveIntent()remains available for mapping boundaries, but field-specific getters are preferred when only a few values are needed.Notes
Validation
make lintmake test-nocacheSummary by CodeRabbit