Skip to content

fix: child unique reference handling - #4385

Merged
turip merged 12 commits into
mainfrom
fix/child-unique-reference-handling
May 19, 2026
Merged

turip merged 12 commits into
mainfrom
fix/child-unique-reference-handling

Conversation

@turip

@turip turip commented May 19, 2026 •

Copy link
Copy Markdown
Member

Overview

This patch makes sure that for charges based billing we are relying on the ChargeID to identify children instead of ChildUniqueReferenceID.

That was only used when we didn't have a central object. Unfortunately this affected the already converted testcases, so a new assertion method is added with charges focus.

Notes for reviewer

Summary by CodeRabbit

  • New Features

    • Added ability to force invoice collection immediately, bypassing the standard collection period.
  • Changes

    • Invoice actions awaiting collection now trigger force-collection behavior instead of snapshotting quantities.
    • Gathering/invoice lines no longer include per-child unique reference IDs, changing how some charge lines are represented.
  • Tests

    • Improved charge assertion tests for more robust end-to-end verification.
  • Documentation

    • Added Postgres troubleshooting guidance for test failures.

Review Change Stack

@turip
turip requested a review from a team as a code owner May 19, 2026 14:18
@coderabbitai

coderabbitai Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

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: 366fffdc-945e-4a51-bcbf-e7ebc3358859

📥 Commits

Reviewing files that changed from the base of the PR and between 3079dda and f673efc.

📒 Files selected for processing (2)
  • openmeter/billing/worker/subscriptionsync/service/base_test.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/billing/worker/subscriptionsync/service/base_test.go

📝 Walkthrough

Walkthrough

Replaces SnapshotQuantities with a ForceCollect flow (trigger, service API, HTTP handler, and state machine); adds Service.ForceCollectInvoice; removes ChildUniqueReferenceID from gathering-line creation; adds Charge.GetUniqueReferenceID; refactors subscription-sync charge assertion tests and related test doubles; adds a SKILL troubleshooting note.

Changes

Invoice Force Collection and Charge Reference Updates

Layer / File(s) Summary
Trigger definition and state machine
openmeter/billing/stdinvoicestate.go, openmeter/billing/stdinvoice.go, openmeter/billing/service/stdinvoicestate.go
Adds TriggerForceCollect and ForceCollectInvoiceInput alias; updates DraftWaitingForCollection transition to use TriggerForceCollect; computes availableActions.SnapshotQuantities from TriggerForceCollect.
Service interface and HTTP wiring
openmeter/billing/service.go, openmeter/billing/service/invoice.go, openmeter/billing/httpdriver/invoice.go
Adds InvoiceService.ForceCollectInvoice, implements Service.ForceCollectInvoice via executeTriggerOnInvoice with TriggerForceCollect, and updates the HTTP snapshot_quantities action to call ForceCollectInvoice.
Charge GetUniqueReferenceID and gathering-line cleanup
openmeter/billing/charges/charge.go, openmeter/billing/charges/flatfee/service/create.go, openmeter/billing/charges/usagebased/service/create.go
Introduces Charge.GetUniqueReferenceID() that returns the intent's UniqueReferenceID by charge type; removes ChildUniqueReferenceID assignments from gathering-line GatheringLineBase in flat-fee and usage-based builders.
Test helper refactor and tooling note
openmeter/billing/worker/subscriptionsync/service/base_test.go, openmeter/server/server_test.go, .agents/skills/test/SKILL.md
Unifies charge assertion helpers into matcher-driven expectations and helpers; updates NoopBillingService test double to implement ForceCollectInvoice; adds Postgres-backed test troubleshooting note.

Sequence Diagram

sequenceDiagram
  participant HTTPHandler as ProgressInvoice handler
  participant Service as Service.ForceCollectInvoice
  participant Executor as executeTriggerOnInvoice
  participant State as stdinvoicestate (TriggerForceCollect)

  HTTPHandler->>Service: call ForceCollectInvoice(invoiceID)
  Service->>Executor: executeTriggerOnInvoice(invoiceID, TriggerForceCollect)
  Executor->>State: fire TriggerForceCollect -> transition DraftWaitingForCollection -> DraftCollecting
  State-->>Executor: transition result (StandardInvoice)
  Executor-->>Service: return StandardInvoice
  Service-->>HTTPHandler: return StandardInvoice response
Loading

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly Related PRs

  • openmeterio/openmeter#4363: Changes the same gathering-line creation path for flat-fee charges (also touches ChildUniqueReferenceID/line creation).

Suggested Reviewers

  • tothandras
  • GAlexIHU
  • mark-vass-konghq
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% 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 'fix: child unique reference handling' accurately summarizes the main change: refactoring how the system identifies charges by using ChargeID instead of ChildUniqueReferenceID.
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 fix/child-unique-reference-handling

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 and usage tips.

@turip turip changed the title Fix/child unique reference handling fix: child unique reference handling May 19, 2026
@turip turip added release-note/bug-fix Release note: Bug Fixes area/billing labels May 19, 2026

@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

🧹 Nitpick comments (1)
openmeter/billing/worker/subscriptionsync/service/base_test.go (1)

519-522: ⚡ Quick win

Use the repo’s preferred decimal assertion style in tests

Could we align this with the test guideline and compare InexactFloat64() via require.Equal here?

Example adjustment
- s.AssertDecimalEqual(expectedFlatPrice.Amount, flatFeeCharge.Intent.AmountBeforeProration, fmt.Sprintf("%s: amount before proration", childID))
+ require.Equal(
+   s.T(),
+   expectedFlatPrice.Amount.InexactFloat64(),
+   flatFeeCharge.Intent.AmountBeforeProration.InexactFloat64(),
+   "%s: amount before proration",
+   childID,
+ )

As per coding guidelines: "When asserting alpacadecimal.Decimal equality in tests, prefer require.Equal(t, expectedFloat64, actual.InexactFloat64()) over boolean assertions, and use simple float64 literals over verbose decimal construction".

🤖 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/base_test.go` around lines
519 - 522, Replace the custom decimal assertion with the repo preferred style:
keep the s.NoError(err) after expectedFlatPrice, then replace
s.AssertDecimalEqual(expectedFlatPrice.Amount,
flatFeeCharge.Intent.AmountBeforeProration, fmt.Sprintf("%s: amount before
proration", childID)) with require.Equal(s.T(),
expectedFlatPrice.InexactFloat64(),
flatFeeCharge.Intent.AmountBeforeProration.InexactFloat64(), fmt.Sprintf("%s:
amount before proration", childID)); reference symbols: expectedFlatPrice,
s.NoError, flatFeeCharge.Intent.AmountBeforeProration, childID, and
require.Equal.
🤖 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/worker/subscriptionsync/service/base_test.go`:
- Around line 559-567: The test currently uses lo.Find to match
expectedRealization against actualRealizations which can reuse the same actual
entry for duplicate keys; change the logic to locate the index of the matching
actualRealization (e.g., iterate actualRealizations or use lo.FindIndex with the
same predicate), assert found, then remove that element from the
actualRealizations slice (consume it) so subsequent matches cannot reuse it;
apply the same consume-on-match change in the other loop (the one around lines
612-619) and in assertChargeGatheringLines to ensure duplicates are handled
correctly.
- Around line 430-433: Add a nil guard before accessing expectedCharge.Matcher
in the loop that iterates expectedCharges: assert that expectedCharge.Matcher is
not nil (e.g., with s.Require().NotNil(expectedCharge.Matcher, "expected charge
matcher")) prior to calling expectedCharge.Matcher.ChildIDs(subscriptionID.ID)
so a missing matcher fails with a readable assertion; update the loop in
base_test.go where expectedCharge.Matcher.ChildIDs is invoked to perform this
check (and only call ChildIDs after the nil assertion).

---

Nitpick comments:
In `@openmeter/billing/worker/subscriptionsync/service/base_test.go`:
- Around line 519-522: Replace the custom decimal assertion with the repo
preferred style: keep the s.NoError(err) after expectedFlatPrice, then replace
s.AssertDecimalEqual(expectedFlatPrice.Amount,
flatFeeCharge.Intent.AmountBeforeProration, fmt.Sprintf("%s: amount before
proration", childID)) with require.Equal(s.T(),
expectedFlatPrice.InexactFloat64(),
flatFeeCharge.Intent.AmountBeforeProration.InexactFloat64(), fmt.Sprintf("%s:
amount before proration", childID)); reference symbols: expectedFlatPrice,
s.NoError, flatFeeCharge.Intent.AmountBeforeProration, childID, and
require.Equal.
🪄 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: 900d2f95-98ee-4448-ba7d-37338d05876e

📥 Commits

Reviewing files that changed from the base of the PR and between 101366b and fef7a49.

📒 Files selected for processing (3)
  • .agents/skills/test/SKILL.md
  • openmeter/billing/worker/subscriptionsync/service/base_test.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go

@turip
turip force-pushed the fix/child-unique-reference-handling branch from fef7a49 to 3079dda Compare May 19, 2026 14:55
@turip
turip merged commit 7cddb66 into main May 19, 2026
26 checks passed
@turip
turip deleted the fix/child-unique-reference-handling branch May 19, 2026 17:00

This branch was previously deployed

1 inactive deployment
dev — f673efcc Deployed May 19, 2026 by turip via Migration Checks #14499
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants